//头文件
#ifndef _MYHEAD_H
#define _MYHEAD_H
//把所有常用的头文件全部包含
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <stdbool.h>
#include <unistd.h>
#include <errno.h> //跟perror有关
#include <linux/input.h> //跟输入子系统模型有关
#include <sys/wait.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdlib.h>
#endif
//其中之一进程程序
#include "myhead.h"
int main()
{
int n;
int ret;
int fd;
char sbuf[100];
//判断有名管道是否存在
if(access("/home/gec/myfifo",F_OK)!=0) //文件不存在
{
//创建有名管道
ret=mkfifo("/home/gec/myfifo",0777);
if(ret==-1)
{
perror("创建有名管道失败了!\n");
return -1;
}
}
//打开刚才新建的有名管道
fd=open("/home/gec/myfifo",O_RDWR);
if(fd==-1)
{
perror("打开管道失败了!\n");
return -1;
}
//p1键盘输入字符串,通过有名管道发送给p2
while(1)
{
bzero(sbuf,100);
printf("请输入要发送给p2进程的信息!\n");
n=getpid();
//写入到有名管道中
write(fd,&n,sizeof(int));
sleep(1);
}
//关闭
close(fd);
return 0;
}
//其中之一的进程程序
#include "myhead.h"
int main()
{
pid_t n;
int k;
int ret;
int fd;
char rbuf[100];
if(access("/home/gec/myfifo",F_OK)!=0)
{
ret=mkfifo("home/gec/myfifo",0777);
if(ret==-1)
{
perror("创建有名管道失败!\n");
return -1;
}
}
//打开刚才新建的有名管道
fd=open("/home/gec/myfifo",O_RDWR);
if(fd==-1)
{
perror("打开管道失败\n");
return -1;
}
while(1)
{
bzero(rbuf,100);
n=0;
read(fd,&n,sizeof(int));
printf("p1给我发的信息是:%s\n",rbuf);
printf("----------------输入1停止P1--------------------\n");
printf("----------------输入2继续P1--------------------\n");
printf("----------------输入3停止P1--------------------\n");
scanf("%d",&k);
if(k==1)
{
kill(n,19);
}
else if(k==2)
{
// system();
}
else if (k==3)
{
//system();
}
}
close(fd);
return 0;
}
有名管道双向通信
最新推荐文章于 2024-08-12 10:43:06 发布