Linux进程间通信之管道通信

本文详细介绍了Linux进程间通信的一种方式——管道通信,包括管道的特点、创建方法及读写操作。通过示例代码展示了如何利用管道进行父子进程间的通信。

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

Linux进程间通信之管道通信

管道的一些特点如下:

它只能用于有亲缘关系的进程之间的通信(父子进程或兄弟进程)

它是一个半双工的通信模式,有固定读端、写端

管道可以看成一种特殊的文件,读写可以使用普通的read、write等函数

 

1.管道创建

prototype : int pipi(int fd[2])

input : fd[2],管道的两个文件描述符,成功创建管道之后可以直接操作

output: 0 —— success

            -1 —— failure

 

例子:

[c-sharp] view plain copy
  1. #include <unistd.h>  
  2. #include <errno.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5.   
  6. int main(void)  
  7. {  
  8.     int pipe_fd[2];  
  9.   
  10.     if (pipe(pipe_fd) < 0)  
  11.     {  
  12.         printf("pipe create error/n");  
  13.         return -1;  
  14.     }  
  15.     else  
  16.     {  
  17.         printf("pipe create success/n");  
  18.     }  
  19.       
  20.     close(pipe_fd[0]);  
  21.     close(pipe_fd[1]);  
  22. }  

 

2.管道读写

创建管道之后,有两个文件描述符,分别是fd[0]和fd[1],其中fd[0]是读取端,fd[1]是写入端。以下例子中,子进程作为读取端(需要关闭其写入端),父进程作为写入端(关闭其读取端)。贴出代码如下:

[c-sharp] view plain copy
  1. #include <unistd.h>  
  2. #include <sys/types.h>  
  3. #include <errno.h>  
  4. #include <stdio.h>  
  5. #include <stdlib.h>  
  6.   
  7. int main(void)  
  8. {  
  9.     int pipe_fd[2];  
  10.     pid_t pid;  
  11.     char buf_r[100];  
  12.     char* p_wbuf;  
  13.     int r_num;  
  14.   
  15.     memset(buf_r, 0, sizeof(buf_r));  
  16.   
  17.     if (pipe(pipe_fd) < 0)  //创建管道  
  18.     {  
  19.         printf("pipe create error/n");  
  20.         return -1;  
  21.     }  
  22.   
  23.     if ((pid = fork()) == 0)   //进入子进程  
  24.     {  
  25.         printf("/n");  
  26.         close(pipe_fd[1]);  //关闭写端口  
  27.         sleep(2);           //睡眠2s,等待父进程写  
  28.         if ((r_num = read(pipe_fd[0], buf_r, 100)) > 0)      
  29.         {                   //读取管道内容  
  30.             printf("%d numbers read from the pipe is %s/n", r_num, buf_r);  
  31.         }  
  32.         close(pipe_fd[0]);  //关闭读端口  
  33.         exit(0);  
  34.     }  
  35.     else if (pid > 0)       //进入父进程  
  36.     {  
  37.         close(pipe_fd[0]);   //关闭读端口  
  38.         if (write(pipe_fd[1], "jarvis", 6) != -1)  
  39.         {                    //分两次向管道写入  
  40.             printf("parent write_1 jarvis!/n");  
  41.         }  
  42.         if (write(pipe_fd[1], "hello", 5) != -1)  
  43.         {  
  44.             printf("parent write_2 hello!/n");  
  45.         }  
  46.         close(pipe_fd[1]);  
  47.         sleep(3);  
  48.         waitpid(pid, NULL, 0);   //等待子进程结束  
  49.         exit(0);  
  50.     }  
  51. }  

编译并运行,终端打印信息如下:

 

OK,实现管道通信!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值