【C/C++】ftok函数作用和用法

系统建立IPC通讯(如消息队列、共享内存等)  必须指定一个ID值。通常情况下,该id值通过ftok函数得到。
ftok原型如下:

 #include <sys/types.h> 
 #include <sys/ipc.h>

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

 pathname参数:  必须是一个已经存在且程序可范围的文件。

 proj_id参数: 虽然定义为一个整数,其实实际只有8个bit位有效,即如果该参数大于255,则只有后8bit有效。 

 函数作用: convert a pathname and a project identifier to a System V IPC key, Key可用于msgget, semget, or shmget的key参数

示例:

    #define  SHMSIZE   256

    key_t  shmKey = ftok(“/tmp”, 128);
    if (-1 == shmKey)
    {
        printf("ERROR: ftok faield, %s.\n", strerror(errno));
        exit(-1);
    }

    //创建共享内存

    int shmid = shmget(shmKey, SHMSIZE, 0666);
    if (-1 == shmid)
    {
        shmid = shmget(shmKey, SHMSIZE, IPC_CREAT | 0666);
        if (-1 == shmid)
        {
            shmid = shmget(shmKey, 0, 0666);
            if (shmid >= 0)
            {
                shmctl(shmid, IPC_RMID, NULL);
                shmid = shmget(shmKey, SHMSIZE, IPC_CREAT | 0666);
            }
            if (-1 == shmid)
            {
                printf("ERROR: call shmget failed, %s.\n", strerror(errno));
                exit(-1);
            }
       }
   

     //链接共享内存

     char *shmptr  = (char *)shmat(shmid, (char *) 0, 0666);
     if (shmptr  == (char *)(-1))
      {
          printf("Call shmat()  failed, %s.\n", strerror(errno));
          exit(-1);
      }

      memcpy(shmptr, "1234567890", sizeof("1234567890"));
     printf("share memory from %lx to %lx, content:%s\n",(unsigned long)shmptr, (unsigned long)(shmptr + SIZE), shmptr);

     //拆卸共享内存
     if ((shmctl(shmid, IPC_RMID, 0) < 0))
     {
        printf("shmctl error:%s\n", strerror(errno));
        return -1;
     }

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值