Linux 下实现两个管道双向数据流
原文地址:http://www.wangzhongyuan.com/archives/488.html
以下是一个Linux/Unix下由两个管道提供双向数据流的C程序,这是操作系统课程中经常使用的基本程序
#include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <string.h> int main() { int fd1[2],fd2[2],cld_pid,status; char buf[200], len; if (pipe(fd1) == -1) // 创建管道1 { printf("creat pipe1 error\n"); exit(1); } if (pipe(fd2) == -1) // 创建管道2 { printf("creat pipe2 error\n"); exit(1); } if ((cld_pid=fork()) == 0) //子进程 { close(fd1[1]); // 子进程关闭管道1的写入端 close(fd2[0]); // 子进程关闭管道1的读出端 //子进程读管道1 len = read(fd1[0],buf,sizeof(buf)); printf("\n这是在子进程:子进程从管道1中读出的字符串 -- %s",buf); //子进程写管道2 strcpy(buf,"子进程写入管道2的字符串"); write(fd2[1],buf,strlen(buf)); printf("\n这是在子进程:子进程成功写入如下语句:%s\n",buf); exit(0); } else //父进程 { close(fd1[0]); // 父进程关闭管道1的读出端 close(fd2[1]); // 父进程关闭管道2的写入端 //父进程写管道1 strcpy(buf,"父进程写入管道1的字符串"); write(fd1[1],buf, strlen(buf)); printf("miaojing\n"); //父进程读管道2 len = read(fd2[0],buf,sizeof(buf)); printf("\n这是在父进程:父进程从管道2中读出的字符串 -- %s\n",buf); exit(0); } }