实验内容编写程序,让父进程创建两个子进程P1和P2,并使子进程P1和P2通过消息队列相互通信,发送消息(512字节)。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stropts.h>
#include <time.h>
#include <strings.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msg {
long msg_type;
char msg_buf[511];
};
int main (void)
{
int qid, pid, len,ret;
struct msg pmsg1,pmsg2;
pid = fork();
if(pid < 0){
fprintf(stderr,"Fork Failed");
exit(-1);
}
else if(pid == 0){
qid = msgget((key_t)1235, 0666|IPC_CREAT);
if (qid == -1) {
printf("msgget failed!\n");
exit(1);
}
pmsg1.msg_type = 1;
sprintf(pmsg1.msg_buf, "hello! this is :%d\n\0", getpid());//要发送的内容
printf("a");
ret = msgsnd(qid, &pmsg1, 511, 0);
if (ret == -1) {
printf("msgsnd failed!\n");
exit(1);
}
printf("successfully send a message to the p2: %d\n", qid);
}
else{
wait(NULL);
qid = msgget((key_t)1235, 0666|IPC_CREAT);//创建消息队列
if (qid == -1) {
printf("msgget failed!\n");
exit(1);
}
pmsg2.msg_type = 0;
ret = msgrcv(qid, &pmsg2, 511, 0, 0);//接收消息
if (ret == -1) {
printf("msgrcv failed!\n");
exit(1);
}
printf("received form to p1: %s\n", pmsg2.msg_buf);
ret = msgctl(qid, IPC_RMID, 0);//全局性的删除-IPC_RMID
if (ret == -1) {
printf("msgctl(IPC_RMID) failed!\n");
exit(1);
}
exit(0);
}
}
实验结果