实现两个进程之间的互相通信,并且当发送exit时,退出进程
进程间的消息队列的使用和有名管道的使用类似
代码:
小明:
//消息队列
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
int main(int argc,int *argv[])
{
//定义结构体
struct msg_buf
{
long type;//通信标志
char text[1024];//通信数据
};
//获取key
key_t key=ftok(".",10);//这个10是随机写的,但是两个主进程的这个值必须一样
if(key==-1)
{
printf("error\n");
}
//根据key值去创建消息队列
int id=msgget(key,IPC_CREAT|0666);
if(id==-1)
{
printf("error\n");
}
//打印key值和id值
printf("%#x,%d\n",key,id);
//定义一个结构体变量
struct msg_buf data;
//定义两个子进程
pid_t pid1,pid2;
pid1=fork();
pid2=fork();
while(1)
{
if(pid1==0)
{
//进程一 发送数据到小芳
//清空变量
memset(&data,0,sizeof(data));
//写入正文
char input[1024];
fgets(input,1024,stdin);
strcpy(data.text,input);
//初始化数据类型
data.type=250;//暗号
//发送数据
int ret=msgsnd(id, &data,strlen(data.text),0);
if(ret==-1)
{
perror("msgsnd error");
return -3;
}
if(strncmp(input,"exit",4)==0)//判断退出条件
{
//杀死主进程和两个子进程
kill(getppid(),SIGKILL);
kill(pid1,SIGKILL);
kill(pid2,SIGKILL);
exit(0);
}
}
if(pid2==0)
{
//接收来自小芳的数据
memset(&data,0,sizeof(data));//清空
int size=msgrcv(id,&data,sizeof(data.text),10,0);//接收数据
if(size==-1)
{
printf("读取error\n");
}
if(strncmp(data.text,"exit",4)==0)//判断退出条件
{
//杀死主进程和两个子进程
kill(getppid(),SIGKILL);
kill(pid1,SIGKILL);
kill(pid2,SIGKILL);
exit(0);
}
printf("来自小芳的数据的字节数:%d\n",size);
printf("小明收到的数据:%s\n",data.text);
}
}
return 0;
}
小芳
//消息队列
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
int main(int argc,int *argv[])
{
//定义结构体
struct msg_buf
{
long type;//通信标志
char text[1024];//通信数据
};
//获取key
key_t key=ftok(".",10);
if(key==-1)
{
printf("error\n");
}
//根据key值去创建消息队列
int id=msgget(key,IPC_CREAT|0666);
if(id==-1)
{
printf("error\n");
}
//打印key值和id值
printf("%#x,%d\n",key,id);
//定义一个结构体变量
struct msg_buf data;
//定义两个子进程
pid_t pid1,pid2;
pid1=fork();
pid2=fork();
while(1)
{
//接收来自小明的数据
if(pid1==0)
{
memset(&data,0,sizeof(data));//清空
int size=msgrcv(id,&data,sizeof(data.text),250,0);//接收数据
if(size==-1)
{
printf("读取error\n");
}
if(strncmp(data.text,"exit",4)==0)//判断退出条件
{
//杀死主进程和两个子进程
kill(getppid(),SIGKILL);
kill(pid1,SIGKILL);
kill(pid2,SIGKILL);
exit(0);
}
printf("来自小明的数据的字节数:%d\n",size);
printf("小芳收到的数据:%s\n",data.text);
}
if(pid2==0)
{
//发送数据到小明
//清空变量
memset(&data,0,sizeof(data));
//写入正文
char input[1024];
fgets(input,1024,stdin);
strcpy(data.text,input);
//初始化数据类型
data.type=10;//暗号
//发送数据
int ret=msgsnd(id, &data,strlen(data.text),0);
if(ret==-1)
{
perror("msgsnd error");
return -3;
}
if(strncmp(input,"exit",4)==0)//判断退出条件
{
//杀死主进程和两个子进程
kill(getppid(),SIGKILL);
kill(pid2,SIGKILL);
kill(pid1,SIGKILL);
exit(0);
}
}
}
return 0;
}