
作業(yè)社區(qū)
探索學習新天地,共享知識資源!
Linkus 的學生作業(yè):
作業(yè)與內(nèi)容不對,交練習:【圖片】 /* 創(chuàng)建兩個子進程 A B,父進程分別給兩個子進程發(fā)消息,消息類型為100 200 */ /* 父進程從鍵盤讀入數(shù)據(jù),發(fā)送給子進程,輸入quit則退出 */ #include #include #include #include #include #include #include #include #define PATH "." #define PROJ_ID 3 #define MSG_TYPE_A 100 #define MSG_TYPE_B 200 #define MSG_SIZE 64 struct msgbuf{ long type; char text[MSG_SIZE]; }; int main(void) { key_t key; int msgid,ret; pid_t apid,bpid; struct msgbuf msg; ssize_t bytes; key = ftok(PATH,PROJ_ID); if(key == -1) { perror("ftok(): "); exit(EXIT_FAILURE); } msgid = msgget(key,IPC_CREAT | 0644); if(msgid == -1) { perror("msgget(): "); exit(EXIT_FAILURE); } printf("msgid \n",msgid); apid = fork(); if(apid == -1) { perror("fork(): "); exit(EXIT_FAILURE); } else if (apid == 0) { do { bytes = msgrcv(msgid,(void *)&msg,MSG_SIZE,MSG_TYPE_A,0); printf("process A rev msg \n",msg.text); } while(strcmp(msg.text,"quit") != 0); printf("process A exit.\n"); exit(EXIT_SUCCESS); } bpid = fork(); if(bpid == -1) { perror("fork(): "); exit(EXIT_FAILURE); } else if (bpid == 0) { do { bytes = msgrcv(msgid,(void *)&msg,MSG_SIZE,MSG_TYPE_B,0); printf("process B rev msg \n",msg.text); } while(strcmp(msg.text,"quit") != 0); printf("process B exit.\n"); exit(EXIT_SUCCESS); } do { printf("Enter > "); fgets(msg.text,sizeof(msg.text),stdin); msg.text[strlen(msg.text)-1] = '\0'; printf("(Input )\n",msg.text); msg.type = MSG_TYPE_A; if(msgsnd(msgid,(const void *)&msg,strlen(msg.text)+1,0) == -1) { perror("msgsnd(): "); exit(EXIT_FAILURE); } msg.type = MSG_TYPE_B; if(msgsnd(msgid,(const void *)&msg,strlen(msg.text)+1,0) == -1) { perror("msgsnd(): "); exit(EXIT_FAILURE); } sleep(1); } while(strcmp(msg.text,"quit") != 0); wait(NULL); wait(NULL); ret = msgctl(msgid,IPC_RMID,NULL); if(ret == -1){ perror("msgctl(): "); exit(EXIT_FAILURE); } printf("Main Exit.\n"); return 0; }