Linux——管道

本文通过两个实例演示了如何使用无名管道实现父子进程及兄弟进程间的双向和单向通信。详细介绍了管道创建、读写操作及进程间通信的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   前几天学习了管道内容,课本上只有无名管道的单工程序,老师说管道也可以进行双向通信,因此自己练习一下双向通信:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
   pid_t pid;
   int pipe1[2],pipe2[2];
   char str[40];
   if((pipe(pipe1))==-1)
    {
       perror("pipe is failed!!!");
       exit(EXIT_FAILURE);
    }
   if((pipe(pipe2))==-1)
    {
       perror("pipe is failed!!!");
       exit(EXIT_FAILURE);
    }
if((pid=fork())<0)
{
   perror("fork is failed!!!\n");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
  close(pipe1[0]);
  close(pipe2[1]);
  printf("I am a child process!\n");
  if(write(pipe1[1],"child process wtite data to pipe1\n",40)!=-1)
           printf("write data to pipe1 is sucess\n");
  read(pipe2[0],str,40);
       printf("read pipe2=%s",str);
      close(pipe1[1]);
 close(pipe2[0]);
}


else if(pid>0)
{
  sleep(3);
  close(pipe1[1]);
  close(pipe2[0]);
  printf("I am a father process!\n");
   write(pipe2[1],"parent process write data to pipe2\n",40);
        printf("write data to pipe2 is success\n");
read(pipe1[0],str,40);
printf("read pipe1=%s",str);
close(pipe2[1]);
close(pipe1[0]);
        waitpid(pid,NULL,0);
}
return 0;
}

管道的作用是将第一个进程的输出作为第二个进程的输入。
在无名管道单向通信中,pipe[ 2 ] 数组中,pipe[ 0 ] 表示读端,pipe[ 1 ] 表示写端,例如在进行文件读入管道时,首先应该关闭pipe[ 1 ] 写端,打开读端pipe[ 0 ],采用read( int pipeno,char *str,sizeof(sizeof)) 进行读,第一个参数为管道描述符,参数二是字符串,参数三是字符串长度。一定别忘了之后还要关闭读端。在管道中进行写文件时与读端类似。

而双向通信只是创建两个数组,表示两个管道


下面这个是兄弟间的单向通信:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
   pid_t pid1,pid2;
   int pipes[2];
   char str[20];
   if(pipe(pipes)==-1)
   {
      perror("pipe is error\n");
 exit(EXIT_FAILURE);
   }
   pid1=fork();
   if(pid1<0)
       printf("Fork pid1 is error\n");
   else if(pid1==0)
   {
       close(pipes[0]);
    if((write(pipes[1],"We are brothers\n",20))==-1)
    {
       perror("write is error\n");
exit(EXIT_FAILURE);
    }
else
printf("write data to pipe is success\n");
close(pipes[1]);
   }
   else
   {
      pid2=fork();
  if(pid2<0)
       printf("Fork pid2 is error\n");
  else if(pid2==0)
  {
      close(pipes[1]);
    if((read(pipes[0],str,20))==-1)
        {
   perror("read to pipe is error\n");
exit(EXIT_FAILURE);
}
else
printf("read from pipe = %s",str);
close(pipes[0]);
  }    
   }
   return 0;
}

关于子进程的创建采用上一篇的方法和原理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值