key_t鍵和ftok函數(轉)


其實更加應該提醒我們的是,可以使用grep等工具去自己search the answer!

 

key_t鍵

System V IPC使用key_t值作為它們的名字,在Redhat linux(后續驗證默認都在該平台下)下key_t被定義為int類型,追溯如下:

/usr/include/sys/ipc.h

#ifndef __key_t_defined

typedef __key_t key_t;

#define __key_t_defined

#endif

/usr/include/bits/types.h

typedef __DADDR_T_TYPE __daddr_t; /* The type of a disk address.  */
typedef __SWBLK_T_TYPE __swblk_t; /* Type of a swap block maybe?  */
typedef __KEY_T_TYPE __key_t;   /* Type of an IPC key */

/usr/include/bits/typesizes.h

#define __KEY_T_TYPE              __S32_TYPE

/usr/include/bits/types.h

#define       __S32_TYPE              int

ftok函數

  函數ftok把一個已存在的路徑名和一個整數標識得轉換成一個key_t值,稱為IPC鍵:

       # include
       # include

       key_t ftok(const char *pathname, int proj_id);

DESCRIPTION
       The ftok function uses the identity of the  file  named  by  the  given pathname  (which  must  refer  to an existing, accessible file) and the least significant 8 bits of proj_id (which must be nonzero) to generate  a  key_t  type  System  V  IPC  key。

    該函數把從pathname導出的信息與id的低序8位組合成一個整數IPC鍵。

sample:

  #include        "unpipc.h"

  int main(int argc, char **argv)
  {
        struct stat     stat;

        if (argc != 2)
                err_quit("usage: ftok ");

        Stat(argv[1], &stat);
        printf("st_dev: %lx, st_ino: %lx, key: %x/n",
              (u_long) stat.st_dev,
(u_long) stat.st_ino,
              Ftok(argv[1], 0x57));

        exit(0);
  }

程序運行結果:

      [cbs@linux svipc]$ ./ftok  /tmp/mysql.sock
     st_dev: 802, st_ino: 34219, key: 57024219

ftok的典型實現調用stat函數,然后組合以下三個值:
1.pathname所在的文件系統的信息(stat結構的st_dev成員)
2.該文件在本文件系統內的索引節點號(stat結構的st_ino成員)
3. proj_id的低序8位(不能為0)
從程序運行的結果可以看出,ftok調用返回的整數IPC鍵由proj_id的低序8位,st_dev成員的低序8位,st_info的低序16位組合而成。
 
不能保證兩個不同的路徑名與同一個proj_id的組合產生不同的鍵,因為上面所列三個條目(文件系統標識符、索引節點、proj_id)中的信息位數可能大於一個整數的信息位數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM