建立两个.c 建立子父进程,父进程发送消息到队列,子进程读取队列,另一个同样。
#include <myhead.h> struct msga {long mtype;char mtext[1024]; }; #define len sizeof(struct msga)-sizeof(long) int main(int argc, const char *argv[]) {pid_t pid;pid=fork();if(pid>0){key_t key=ftok("./",'L');if(key==-1){perror("ftok");return -1;}int msgID=msgget(key,IPC_CREAT|0664);if(msgID==-1){perror("msgget");return -1;}struct msga send;while(1){printf("请输入消息类型:");scanf("%ld",&send.mtype);getchar();printf("请输入消息内容:");fgets(send.mtext,sizeof(send.mtext),stdin);send.mtext[strlen(send.mtext)-1]='\0';msgsnd(msgID,&send,len,0);if(strcmp(send.mtext,"quit")==0){break;}}if(msgctl(msgID,IPC_RMID,NULL)==-1){perror("msgctl");return -1;}}else if(pid==0){key_t key=ftok("./",'Y');if(key==-1){perror("ftok");return -1;}int msgID=msgget(key,IPC_CREAT|0664);if(msgID==-1){perror("msgget");return -1;}struct msga rev;while(1){msgrcv(msgID,&rev,len,0,0);printf("%s\n",rev.mtext);if(strcmp(rev.mtext,"quit")==0){break;}}if(msgctl(msgID,IPC_RMID,NULL)==-1){perror("msgctl");return -1;}}else{perror("fork");return -1;}return 0; }
#include <myhead.h> struct msga {long mtype;char mtext[1024]; }; #define len sizeof(struct msga)-sizeof(long) int main(int argc, const char *argv[]) {pid_t pid;pid=fork();if(pid>0){key_t key=ftok("./",'Y');if(key==-1){perror("ftok");return -1;}int msgID=msgget(key,IPC_CREAT|0664);if(msgID==-1){perror("msgget");return -1;}struct msga send;while(1){printf("请输入消息类型:");scanf("%ld",&send.mtype);getchar();printf("请输入消息内容:");fgets(send.mtext,sizeof(send.mtext),stdin);send.mtext[strlen(send.mtext)-1]='\0';msgsnd(msgID,&send,len,0);if(strcmp(send.mtext,"quit")==0){break;}}if(msgctl(msgID,IPC_RMID,NULL)==-1){perror("msgctl");return -1;}}else if(pid==0){key_t key=ftok("./",'L');if(key==-1){perror("ftok");return -1;}int msgID=msgget(key,IPC_CREAT|0664);if(msgID==-1){perror("msgget");return -1;}struct msga rev;while(1){msgrcv(msgID,&rev,len,0,0);printf("%s\n",rev.mtext);if(strcmp(rev.mtext,"quit")==0){break;}}if(msgctl(msgID,IPC_RMID,NULL)==-1){perror("msgctl");return -1;}}else{perror("fork");return -1;}return 0; }