1.c代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
struct msgbuf{long int type;char data[128];
};
#define SIZE sizeof(struct msgbuf)-sizeof(long int)
int main(int argc, const char *argv[])
{char buf[128];key_t key = ftok("/", 'g');if(-1 == key){printf("fork error\n");return -1;}int msqid = msgget(key, IPC_CREAT|0664);if(msqid == -1){printf("mssget error\n");return -1;}pid_t pid = fork();if(pid < 0){printf("fork error\n");return -1;}else if(pid == 0)//子进程{struct msgbuf msg = {.type = 2};while(1){bzero(msg.data, sizeof(msg.data));fgets(msg.data, sizeof(msg.data), stdin);msg.data[strlen(msg.data) - 1] = '\0';if(msgsnd(msqid, &msg, SIZE, 0) == -1){printf("msgsnd error\n");return -1;}if(strcmp(msg.data, "quit") == 0){ break;}}exit(EXIT_SUCCESS);}else//父进程{struct msgbuf msg = {.type = 1};while(1){bzero(buf, sizeof(buf));if(msgrcv(msqid, &msg, SIZE, 1, 0) == -1){printf("msgrcv error\n");return -1;}printf("取出的消息为:%s\n", msg.data);if(strcmp(msg.data, "quit") == 0){ break;}}wait(NULL);}if(msgctl(msqid, IPC_RMID, NULL) == -1){printf("msgctl error\n");return -1;}return 0;
}
2.c代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
struct msgbuf{long int type;char data[128];
};
#define SIZE sizeof(struct msgbuf)-sizeof(long int)
int main(int argc, const char *argv[])
{char buf[128];key_t key = ftok("/", 'g');if(-1 == key){printf("fork error\n");return -1;}int msqid = msgget(key, IPC_CREAT|0664);if(msqid == -1){printf("mssget error\n");return -1;}pid_t pid = fork();if(pid < 0){printf("fork error\n");return -1;}else if(pid == 0)//子进程{struct msgbuf msg = {.type = 1}; while(1){bzero(msg.data, sizeof(msg.data));fgets(msg.data, sizeof(msg.data), stdin);msg.data[strlen(msg.data) - 1] = '\0';if(msgsnd(msqid, &msg, SIZE, 0) == -1){printf("msgsnd error\n");return -1;}if(strcmp(msg.data, "quit") == 0){ break;}}exit(EXIT_SUCCESS);}else//父进程{struct msgbuf msg = {.type = 2};while(1){bzero(buf, sizeof(buf));if(msgrcv(msqid, &msg, SIZE, 2, 0) == -1){printf("msgrcv error\n");return -1;}printf("取出的消息为:%s\n", msg.data);if(strcmp(msg.data, "quit") == 0){break;}}wait(NULL);}if(msgctl(msqid, IPC_RMID, NULL) == -1){printf("msgctl error\n");return -1;}return 0;
}
效果图: