我需要在Linux中使用消息操作(msgrcv,msgsnd,msgctl)实现二进制信号量。 我的代码:使用消息操作的二进制信号量
#include<string.h>
#include<time.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/wait.h>
#include<sys/errno.h>
extern int errno; // error NO.
#define MSGPERM 0600 // msg queue permission
#define MSGTXTLEN 60 // msg text length
int msgqid, rc;
int done;
struct msg_buf
{
long mtype;
char mtext[MSGTXTLEN];
} msg,msg2;
int main(int argc,char **argv)
{
msgqid = msgget(IPC_PRIVATE, MSGPERM|IPC_CREAT);
if (msgqid < 0)
{
perror(strerror(errno));
printf("Failed to create message with id = %d\n", msgqid);
return 1;
}
printf("Message %d created\n",msgqid);
// message to send
msg.mtype = 1; // set the type of message
sprintf (msg.mtext, "%s\n", "Old message...");
rc = msgsnd(msgqid, &msg, sizeof(msg.mtext), 0);
if (rc < 0)
{
perror(strerror(errno));
printf("Could not send, rc = %d\n", rc);
}
// message to send
msg.mtype = 1; // set the type of message
sprintf (msg.mtext, "%s\n", "New message...");
rc = msgsnd(msgqid, &msg, sizeof(msg.mtext), 0);
if (rc < 0)
{
perror(strerror(errno));
printf("Could not send, rc = %d\n", rc);
}
// read the message from queue
rc = msgrcv(msgqid, &msg, sizeof(msg.mtext), 0, 0);
if (rc < 0)
{
perror(strerror(errno));
printf("Could not read, rc=%d\n", rc);
}
printf("Received message: %s\n", msg.mtext);
// remove the queue
rc=msgctl(msgqid,IPC_RMID,NULL);
if (rc < 0)
{
perror(strerror(errno));
printf("Deleting message failed, rc=%d\n", rc);
}
printf("Message %d deleted\n",msgqid);
return 0;
}
据我所知消息操作的力学,所述第一消息与FLAG 0,不IPC_NOWAIT发送,因此所述第二消息将不能够被发送。实际上,我的程序正确地打印了旧的消息,但试图发送第二封消息的过程并不像预期的那样结束。
编辑
演习的主要目标是:“使用渠道和信息创建一个二进制信号” 该指令中的示例仅包含这四个函数用法(msgget,msgsnd,msgctl,msgrcv)和一些标志。
您可以备份并描述分配,而不是您的解决方案中感知的障碍吗? – Duck
在编辑部分进行了描述。 – Cheslav
什么是“频道” - 多个msgtypes,多个队列?什么是“一些标志”? – Duck