管道是一种两个进程间进行单项通信的机制
特点如下:
- 数据只能由一个进程流向另一个进程(其中一个读管道,一个写管道);如果要进行双工通信,则需要建立两个管道。
- 管道只能用于父子进程或者兄弟进程间通信
int pipe(int fd[2]);
利用管道实现在父子进程间通信
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstring> #include <fcntl.h> #include <sys/stat.h> /*利用管道实现在父子进程间通信*/ #define INPUT 0 #define OUTPUT 1 int main() { int fd[2]; /*定义子进程号*/ pid_t pid; char buf[256]; int returned_count; /*创建无名管道*/ pipe(fd); /*创建子进程*/ pid = fork(); if (pid < 0) { printf("Error in fork\n"); exit(1); } else if (pid == 0)/*子进程*/ { printf("in the child process...\n"); /*子进程向父进程些数据,关闭管道的读端*/ close(fd[INPUT]); write(fd[OUTPUT], "hello world", strlen("hello world")); exit(0); } else { printf("in the parent process...\n"); /*父进程从管道读取子进程写的数据,关闭管道的写端*/ close(fd[OUTPUT]); returned_count = read(fd[INPUT], buf, sizeof(buf)); printf("%d bytes of data received from child process: %s\n", returned_count, buf); } return 0; } /*利用管道实现在父子进程间通信*/