【问题标题】:IPC key chose 8 bits from st_dev and 16 bits from st_inoIPC 密钥从 st_dev 中选择了 8 位,从 st_ino 中选择了 16 位
【发布时间】:2013-08-22 01:28:16
【问题描述】:

这是来自 UNP Richard Stevens 的代码副本

   #include "apue.h"                                                                                
   #include <sys/ipc.h>
   int main(int argc,char * argv[])
   {
       struct stat stat_buf;
       if(argc != 2)
           err_quit("usage ftock <pathname>");
       stat(argv[1],&stat_buf);
       printf("st_dev :%08lx, st_info : %08lx ,key :%08x\n",(unsigned long)stat_buf.st_dev,(unsigned long)stat_buf.st_ino,ftok(argv[1],0x57));
   }

输出:

st_dev :00000803, st_ino : 018e17c3 ,key :570317c3

所以密钥从 id 获取 8 位,从 st_dev 获取 8 位,从 st_ino 获取 16 位。

我使用 SUSE gcc。

我知道这本书有点旧了。新工具有新方法。

谁能告诉我ftok工作原理?从st_ino 中选择更多位的原因是什么?

【问题讨论】:

    标签: c linux unix ipc


    【解决方案1】:

    对于设备上的每个文件,每个 inode 都是不同的。每个设备编号对于每个设备(分区)都是唯一的。由于每个设备的文件通常比每个系统的设备多得多,因此如果您想减少冲突的可能性,则使用来自st_ino 的位比来自st_dev 的更多位是有意义的。

    不幸的是,由于ftok 不保证唯一性,任何使用它的应用程序都必须能够容忍冲突。据我所知,这使其或多或少毫无用处。

    【讨论】:

      【解决方案2】:
      key_t
      ftok (pathname, proj_id)
           const char *pathname;
           int proj_id;
      {
        struct stat64 st;
        key_t key;
      
        if (__xstat64 (_STAT_VER, pathname, &st) < 0)
          return (key_t) -1;
      
        key = ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16)
           | ((proj_id & 0xff) << 24));
      
        return key;
      }
      

      这里是 glibc 2.17 的源代码。如你所见,还是一样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多