【发布时间】:2023-03-03 08:57:14
【问题描述】:
我正在尝试创建一个消息队列,然后向它发送消息。这是我尝试过的:
int main(){
int myMsgQueue;
struct msgStruct{
long mtype;
char mtext[LENGTH];
};
struct msgStruct myMsg;
myMsg.mtype = (long)getpid();
strcpy(myMsg.mtext,"Hey there"); //Setting the string of the message
if((myMsgQueue = msgget(IPC_PRIVATE,IPC_CREAT | IPC_EXCL)) == -1) //Creating the message queue
errore(__LINE__);
if(msgsnd(myMsgQueue,&myMsg,sizeof(myMsg) - sizeof(long),0) == -1) //Sending the message
errore(__LINE__);
if(msgctl(myMsgQueue,IPC_RMID,0) == -1) //Deleting the message queue
errore(__LINE__);
}
函数 errore 只是打印出一个字符串,它使用 strerror(errno) 来解释错误。
但是,代码似乎不起作用:errore 在 msgsnd 返回 -1 时打印“Permission denied”。
我无法弄清楚问题出在哪里:我正在初始化消息队列和适当的消息结构,然后创建与进程的 pid 对应的类型的消息和与“嘿,那里”对应的文本,然后发送消息。
我错过了什么?
【问题讨论】:
-
您在
msgget()中遗漏了一些非常重要的内容。密切关注其文档。 -
@Shawn 你说得对,我注意到我还应该在第二个运算符中指定队列的权限!
标签: c message-queue system-calls errno