c - 使用ftok()创建 key 以及如何使用 key ?

标签 c data-structures message-queue embedded-linux

我正在对消息队列进行一些编码。
ftoK()有什么用?
什么是 key 创建?
key 有什么用?
在我的代码中,我使用它作为键“(key_t)1234”,代码运行良好。 这个键“(key_t)1234”的含义是什么? 我如何创建自己的 key ?

发件人:

struct mesg_q
{
    char msg_txt[100];
    long msg_typ;
};

int main()
{
    int msgid;
    //key_t msg_key;
    char buffer[100]; 

    struct mesg_q msgq;
    msgid=msgget((key_t)1234, 0666 | IPC_CREAT);

    if(msgid== -1)
    {    
        printf("msgget failed\n");
        return -1;
    }

    while(1)
    { 
        printf("Text Message\n");
        fgets(msgq.msg_txt,100,stdin);

        if(msgsnd(msgid,&msgq,100,0)==-1)
        {
            printf("Send failed\n");
            return -1;
        }  
        else
        {
            printf("Message send\n");
        }    
    }   
}    

接收器:

struct mesg_q
{
    char msg_txt[100];
    long msg_typ;
};

int main()
{
    int msgid;
    char buffer[100];
    long int rec_buff=0;
    key_t key;
    struct mesg_q msgq;
    msgid=msgget((key_t)1234, 0666 | IPC_CREAT);

    if(msgid == -1)
    {
        printf("Msgget failed\n");
        return -1;
    }

    while(1)
    {
        if(msgrcv(msgid,&msgq,100,rec_buff,0)==-1)
        {
            printf("Mesg recv failed\n");
            return -1;
        }
        else
        {
            printf("Mesg Recvd\n");
        }
        printf("Recvd mesg=%s\n",msgq.msg_txt);
    }     
}

最佳答案

首先,我正在对消息队列进行一些编码。 ftoK()有什么用 和 key 的创建? key 有什么用? 阅读手册页 ftok 它说

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

The ftok() function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) and Today proj_id is an int, but still only 8 bits are used. Typical usage has an ASCII character proj_id, that is why the behavior is said to be undefined when proj_id is zero.

ftok 要求文件存在,因为它使用该文件的inode信息来创建 key .

其次,这个键“(key_t)1234”的含义是什么?检查msgget()第一个参数,它是key_t类型,并且 1234 不是 key_t 类型,它是一个整数,因此您将其类型转换为 key_t 类型。

在您的代码中,您没有使用 ftok() 创建key,您可以像这样创建它。

key_t key;
key = ftok("file.c", 'b'));/*instead of taking random 1234, you are generating key from file based on proj_id */
msgid=msgget(key_t, 0666 | IPC_CREAT);

key有什么用? key是除了消息队列id之外,内核中标识消息队列的标识符之一。在命令行上运行 ipcs -q 并检查。

查看此Whats is purpose ftok in Message queues

关于c - 使用ftok()创建 key 以及如何使用 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50096350/

相关文章:

java - 节点数组如何工作?

for-loop - Golang 中的事件驱动模型

java - 我们如何保存Java消息队列以供引用?

c - 将 movsbl 汇编为 C 代码

data-structures - 设计合并 session 日程的数据结构

algorithm - 用最小的总和制作独特的数组

java - TIBCO 尝试确认对此消费者无效的消息

c - 为链接器生成目标文件 (.o)

c - 使用 sscanf 解析不会保留数组以供后续使用

c - 尝试用 C 语言编写哈希表,我在这里做的事情正确吗?