我正在对消息队列进行一些编码。
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
并检查。
关于c - 使用ftok()创建 key 以及如何使用 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50096350/