父子进程通过管道通讯------命名管道

    Unix编程。创建了两个命名管道,利用这两个管道实现父子进城的通讯。即父进程可以像子进程发送消息,可以读取子进程的消息。子进程一样。下面是全部源码。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <err.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>   

 int main(){
 char buf[1024]; //缓冲区,用来存放读取的内容。
 pid_t pid;//进程标识
 char pipe[]="./fifo";
 memset(buf,0,sizeof(buf));//清空缓冲区的内容 
 if(mkfifo(pipe,0660))//0660具有读写权限

{
    printf(“创建管道失败!");

    exit(1);


   if((pid=fork())<0)

{
    printf(“创建进程失败!");

    exit(1);

else if(pid==0)//子进程

{  

  int fd=open(pipe,O_RDWR);
  char content[]="这是子进程!\n";  
  write(fd,content,sizeof(content));
  read(fd,buf,sizeof(buf));
  printf("子进程收到的消息:%s",buf);
 }
 else//父进程

{

  int fd=open(pipe,O_RDWR);
  char content[]="这里是父进程\n";
  read(fd,buf,sizeof(buf));
  printf("父进程接受的消息: %s",buf);
  write(fd,content,sizeof(content));
 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值