设计程序
使用消息队列实现两个进程之间的信息互通
snd.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>
#include <unistd.h>/*消息发送者
*/// 消息结构体如下:
struct msg_st
{long int msg_type;char text[1024];
};
int main()
{int running = 1;struct msg_st data;char buffer[1024];int msgid = -1;msgid = msgget((key_t)1234, 0666 | IPC_CREAT);//获取消息msg的id,1234来指定同一个IPC对象,即消息队列对象if(msgid == -1){fprintf(stderr, "msgget failed with error:%d\n", errno);exit(EXIT_FAILURE);}while(running){printf("Enter some text: ");fgets(buffer, 1024, stdin);data.msg_type = 1;strcpy(data.text, buffer);if(msgsnd(msgid, (void*)&data, 1024, 0) == -1){fprintf(stderr, "msgsnd failed\n");exit(EXIT_FAILURE);}if(strncmp(buffer, "end", 3) == 0)running = 0;sleep(1);}exit(EXIT_SUCCESS);
}
rcv.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>/*消息接收者
*/
struct msg_st
{long int msg_type;char text[1024];
};
int main()
{int running = 1;int msgid = -1;struct msg_st data;long int msgtype = 0;msgid = msgget((key_t)1234, 0666 | IPC_CREAT);if(msgid == -1){fprintf(stderr, "msgget failed with error:%d\n", errno);exit(EXIT_FAILURE);}while(running){if(msgrcv(msgid, (void*)&data, 1024, msgtype, 0) == -1)//type为0,返回队列中第一个消息,即获取第一个消息{fprintf(stderr, "msgrcv failed with errno:%d\n", errno);exit(EXIT_FAILURE);}printf("You wrote: %s",data.text);if(strncmp(data.text, "end", 3) == 0)running = 0;}if(msgctl(msgid, IPC_RMID, 0) == -1)//删除IPC对象{fprintf(stderr, "msgctl(IPC_RMID) failed\n");exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);
}
gcc -o snd snd.c
gcc -o rcv rcv.c