pipe 函数
管道是一种两个进程间进行单向通信的机制;因为管道传递数据的单向性,管道又称为半双工管道。
Linux 进程间通讯方式:
- 管道(pipe)和有名管道(fifo)
- 消息队列
- 共享内存
- 信号量
- 信号(signal)
- 套接字(sicket)
头文件
函数原型
返回值:
功能
创建一个简单的管道,若成功则为数组 fd 分配两个文件描述符,其中 fd[0] 用于读取管道,fd[1] 用于写入管道。
例子
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 
 | #include <unistd.h>#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 int main(int argc ,char *argv[])
 {
 int pipefd[2],result;
 char buf[1024];
 int exitFlag = 0;
 pid_t fpid;
 
 result = pipe(pipefd);
 if(-1 == result)
 {
 perror("创建管道失败: ");
 exit(EXIT_FAILURE);
 }
 
 fpid = fork();
 if(-1 == fpid)
 {
 perror("创建新进程失败: ");
 exit(EXIT_FAILURE);
 }
 else if(0 == fpid)
 {
 if(-1 == (close(pipefd[1])))
 {
 perror("关闭可写管道失败: ");
 exit(EXIT_FAILURE);
 }
 while(1)
 {
 read(pipefd[0], buf, 1024);
 fprintf(stdout, "读取到内容:%s\n", buf);
 if(0 == strcmp(buf, "exit"))
 {
 exit(EXIT_SUCCESS);
 }
 }
 }
 else
 {
 if(-1 == (close(pipefd[0])))
 {
 perror("关闭可读管道失败: ");
 exit(EXIT_FAILURE);
 }
 while(1)
 {
 waitpid(fpid, NULL, WNOHANG);
 
 if(1 == exitFlag)
 {
 exit(EXIT_SUCCESS);
 }
 scanf("%s", buf);
 write(pipefd[1], buf, strlen(buf) + 1);
 if(0 == strcmp(buf, "exit"))
 {
 exitFlag = 1;
 sleep(1);
 }
 }
 }
 return 1;
 }
 
 | 
运行结果
| 12
 3
 4
 5
 
 | 进程间通信读取到内容:进程间通信
 exit
 读取到内容:exit
 Program ended with exit code: 0
 
 |