有名管道双向通信

//头文件
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值