为了账号安全,请及时绑定邮箱和手机立即绑定

作业社区

探索学习新天地,共享知识资源!

0 提交作业
0 布置作业
0 满分作业
得分 100
学习任务

慕运维8597106 的学生作业:

#include #include #include #include #include #include #include #include #define PATH "." #define PRO_ID 99 #define MSG_TYPEA 100 #define MSG_TYPEB 200 #define MSG_SZ 64 struct msgbuf { long mtype; char mtext[MSG_SZ]; }; void send_message(int msgid, int messageType, char *buf) { struct msgbuf msg; msg.mtype = messageType; strcpy(msg.mtext, buf); int ret = msgsnd(msgid, &msg, strlen(msg.mtext) + 1, 0); } void receive_message(int msgid, struct msgbuf *rcv_msg, int messageType) { int ryptes = msgrcv(msgid, rcv_msg, MSG_SZ, messageType, 0); if (ryptes == -1) { perror("[ERROR] msgrcv"); } if (strcmp(rcv_msg->mtext, "quit") == 0) { printf("进程%d下线了\n", messageType); exit(EXIT_SUCCESS); } printf("进程%d收到消息队列中的数据 类型:%ld 内容:%s\n", messageType, rcv_msg->mtype, rcv_msg->mtext); } int main(int argc, char const *argv[]) { key_t key, msgid; char buf[64] = {0}; int ret; int cpidA, cpidB; struct msgbuf rcv_msg; int ryptes; key = ftok(PATH, PRO_ID); if (key == -1) { perror("[ERROR] ftok : "); exit(EXIT_FAILURE); } msgid = msgget(key, IPC_CREAT | 0666); if (msgid == -1) { perror("[ERROR] msgget : "); exit(EXIT_FAILURE); } cpidA = fork(); if (cpidA == -1) { perror("[ERROR] fork"); exit(EXIT_FAILURE); } else if (cpidA == 0) { while (1) { receive_message(msgid, &rcv_msg, MSG_TYPEA); } } else if (cpidA > 0) { cpidB = fork(); if (cpidB == -1) { perror("[ERROR] fork"); exit(EXIT_FAILURE); } else if (cpidB == 0) { while (1) { receive_message(msgid, &rcv_msg, MSG_TYPEB); } } else if (cpidB > 0) { } } while (1) { fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; send_message(msgid, MSG_TYPEA, buf); send_message(msgid, MSG_TYPEB, buf); if (strcmp(buf, "quit") == 0) { waitpid(cpidA, NULL, 0); waitpid(cpidB, NULL, 0); exit(EXIT_SUCCESS); } } return 0; } 执行结果 linux@linux:~/learn/chapter12/new/job1-16$ ./a.out ls 进程100收到消息队列中的数据 类型:100 内容:ls 进程200收到消息队列中的数据 类型:200 内容:ls ts 进程100收到消息队列中的数据 类型:100 内容:ts 进程200收到消息队列中的数据 类型:200 内容:ts js 进程100收到消息队列中的数据 类型:100 内容:js 进程200收到消息队列中的数据 类型:200 内容:js quit 进程200下线了 进程100下线了 linux@linux:~/learn/chapter12/new/job1-16$

微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号