#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#define SIZE 1024
typedef struct _msg
{
int type;
char data[SIZE];
}MSG;
int main(int argc, char *argv[])
{
int msgqid;
MSG msg;
key_t key= ftok("/tmp",99);
msgqid = msgget(key, IPC_CREAT|0666);
if(-1==msgqid)
{
perror("msgget");
exit(-1);
}
pid_t pid=fork();
if (pid<0)
{
perror("fork");
exit(-1);
}
if (0==pid)
{//子进程
msg.type=66;//指定消息类型,在接收消息时可以指定接收该类型消息
while(1)
{
bzero(msg.data,SIZE);
usleep(200);
printf("In child process send >>> ");
//scanf("%s",&msg.data[0]);
fgets(msg.data, SIZE-1, stdin);
msgsnd(msgqid,&msg,sizeof(MSG)-sizeof(int),0);//发送不成功阻塞
if(!strcmp(msg.data,"quit"))
break;//用户输入了
在一个父进程不断获得键盘的输入,发送到消息队列里,在子进程里不断读取消息队列的内容并送屏幕显示。可添加退出条件,当输入“quit”时退出。
最新推荐文章于 2023-11-05 20:10:09 发布