该进程创建n个子节点(n从stdin读取),并且每个子节点必须在每2秒后向父节点发送一条消息,然后将其收到的每条消息发送给所有子节点。我正在使用2个消息队列:一个是所有子节点将msg发送给父节点,另一个是父节点发送消息并且每个子节点都读取。成功发送或接收的每个孩子都会打印出来自msg队列的pid和数据(数据只是一个随机数)。 但是程序显示错误“msgsnd:invalid arguments”。 我做了一些调试来检查传递的参数是否为null或无效,但事实并非如此。 Noe我有点卡住而且不确定如何继续。任何帮助将不胜感激。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <time.h>
typedef struct msgbuf {
long mtype;
int num;
} message_buf;
long n;
void sigalrm(int signo){
alarm(5);
n=n+2;
printf("%ld seconds elapsed\n",n);
}
int main(int argc,char *argv[]){
int id1,id2;
int msgflg = IPC_CREAT | 0666;
key_t key1,key2;
key1 = ftok ("test2.c", 'A');
key2 = ftok ("test2.c", 'B');
message_buf sbuf,rbuf;
size_t buf_length=sizeof(int);
time_t t;
pid_t pid;
int i,j,k,n;
n=atoi(argv[1]);
if ((id1 = msgget(key1, msgflg )) < 0) {
perror("msgget");
}
else
printf("Queue 1 created\n");
if ((id2 = msgget(key2, msgflg )) < 0) {
perror("msgget");
}
else
printf("Queue 2 created\n");
for(i=0;i<n;i++) {
pid = fork();
if(pid==0) {
setpgid(getpid(),getppid());
signal(SIGALRM, sigalrm);
alarm(2);
while(1) {
srand((unsigned)time(&t));
sbuf.mtype = i;
sbuf.num=rand()%50;
if (msgsnd(id1, &sbuf, buf_length,0) < 0) {
perror("msgsnd");
}
else {
printf("msg sending successful\n");
printf("%ld\t%d\n",(long)getpid(),sbuf.num);
}
pause();
// paused so that now parent can send the messages before children receive it
for(j=0;j<n;j++) {
if (msgrcv(id2, &rbuf, buf_length, j, 0) < 0) {
perror("msgrcv");
}
else {
printf("msg receiving successful\n");
printf("%ld\t%d\n",(long)getpid(),sbuf.num);
}
}
}
}
else if(pid>0) {
while(1) {
sleep(3);
//sleeping so that children can first send the message
if (msgrcv(id1, &rbuf, buf_length,0, IPC_NOWAIT) < 0) {
perror("msgrcv");
}
else {
printf("msg receiving successful\n");
sbuf.num=rbuf.num;
sbuf.mtype=rbuf.mtype;
for(k=0;k<n;k++) {
if (msgsnd(id2, &sbuf, buf_length, IPC_NOWAIT) < 0) {
perror("msgsnd parent\n");
//exit(1);
}
}
}
}
}
}
}
输出:
Queue 1 created
Queue 2 created
msgsnd: Invalid argument
2 seconds elapsed
msgrcv: No message of desired type
msgrcv: No message of desired type
4 seconds elapsed
msgrcv: Interrupted system call
msgrcv: No message of desired type
6 seconds elapsed
msgrcv: Interrupted system call
msgrcv: No message of desired type
msgrcv: No message of desired type
8 seconds elapsed
msgrcv: Interrupted system call
(used ctrl+c here).
答案 0 :(得分:4)
... mtype字段必须具有严格正整数值。 ...
...
<强> EINVAL 强>
无效的msqid值,或非正确的mtype值或无效的msgsz 值(小于0或大于系统值MSGMAX)。
您无法发送mtype
设置为零的消息。