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

作业社区

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

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

别摸我的键盘 的学生作业:

#include #include #include #include #include #include #include #include #include #define PATH "." #define PROID 88 #define MAX 256 #define MSG_TYPE1 100 #define MSG_TYPE2 200 typedef struct msgbuf{ long mtype; char buf[MAX]; }msgbuf_t; int child_rcvmsg(int msg_type){ msgbuf_t data; key_t key = ftok(PATH, PROID); int msg_id = msgget(key, IPC_CREAT | 0666); int ret_bytes = msgrcv(msg_id, (void *)&data, MAX, msg_type,0); if(ret_bytes == -1){ perror("msgrcv()"); return -1; } printf("msg type is %ld\n", data.mtype); printf("msg data is %s\n", data.buf); return 0; } int main(int argc, const char *argv[]) { int a_pid = fork(); if(a_pid == -1){ perror("fork()"); exit(EXIT_FAILURE); }else if(a_pid == 0){ //A child process while(1){ child_rcvmsg(MSG_TYPE1); sleep(1); } }else if(a_pid > 0){ //main process int b_pid = fork(); if(b_pid == -1){ perror("b fork()"); exit(EXIT_FAILURE); }else if(b_pid == 0){ //B child process while(1){ child_rcvmsg(MSG_TYPE2); sleep(1); } }else if(b_pid > 0){ //main process //craete queue key_t key; int msg_id; int idx = 0; msgbuf_t data; int ret; key = ftok(PATH, PROID); if(key == -1){ perror("ftok()"); exit(EXIT_FAILURE); } msg_id = msgget(key, IPC_CREAT | 0666); if(msg_id == -1){ perror("msgget()"); exit(EXIT_FAILURE); } printf("please input data send child pid\n"); //send msg while(1){ fgets(data.buf, sizeof(data.buf), stdin); if(data.buf[strlen(data.buf) - 1] == '\n'){ data.buf[strlen(data.buf) -1] = '\0'; } //printf("data.buf is %s\n", data.buf); //sleep(5); if(strcmp(data.buf, "quit")==0){ ret = msgctl(msg_id, IPC_RMID, NULL); if(ret == -1){ perror("msgctl()"); exit(EXIT_FAILURE); } kill(a_pid, SIGKILL); kill(b_pid, SIGKILL); break; } if(idx % 2 == 0){ data.mtype = MSG_TYPE1; }else{ data.mtype = MSG_TYPE2; } ret = msgsnd(msg_id, (const void *)&data, strlen(data.buf) + 1, 0); if(ret == -1){ perror("msgsnd()"); exit(EXIT_FAILURE); } idx ++; } //quit wait(NULL); wait(NULL); exit(EXIT_SUCCESS); } } return 0; }

微信客服

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

帮助反馈 APP下载

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

公众号

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