我需要在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