0
我得到一個錯誤,指出:msgrcv:無效的參數錯誤
msgrcv:無效的參數
這可能是造成這個錯誤?這裏是我的代碼
卑鄙我從家長傳遞消息給孩子,然後我想從孩子傳遞消息給父母,即使我使用基本上相同的代碼爲兩者,它不是沒有爲第二次接收工作。
struct msg {
long int mtype; /* message type */
char mtext[1024]; /* message text */
} msg;
int len, msgflg = 0, msqid, *pint;
pid_t pid;
size_t msgsz = 40;
long int msgtyp;
msqid = msgget(IPC_PRIVATE,S_IRWXU);
char* charpid[250];
msg.mtype = 1;
if (msqid < 0) {
perror("msgget");
exit(1);
}
switch(pid=fork()) //fork child process
{
case 0: //Child process
//receive message from parent
if(msgrcv(msqid,&msg,sizeof msg.mtext, 1,IPC_NOWAIT)>=0){
printf("Serving for client pid #%s",msg.mtext);
asprintf(&charpid[0], "%ld\n", pid);
strncpy(msg.mtext,charpid[0], 1024);
if(msgsnd(msqid,&msg,strlen(msg.mtext),msgflg)<0){
perror("msgsnd");
}
}
else
perror("msgrcv");
msgctl(msqid, IPC_RMID, NULL);
exit(0);
case -1:
printf("fork failed");
exit(2);
break;
default:
//convert pid to string.
asprintf(&charpid[0], "%ld\n", pid);
//set mtext
strncpy(msg.mtext,charpid[0], 1024);
//send message
if(msgsnd(msqid,&msg,strlen(msg.mtext),msgflg)<0){
//report error
perror("msgsnd");
}
//wait for child process to die
wait(NULL);
//receive message from child
if(msgrcv(msqid,&msg,sizeof msg.mtext, msg.mtype,IPC_NOWAIT)>=0){
//print pid
printf("Received reply from pid #%s",msg.mtext);
}
else
//report error
perror("msgrcv");
exit(0);
}