Linux系统调用pipe函数,创建一个pipe,通过传入的fd数组返回pipe的读、写两端。
其中fd[ 0 ]用于读,fd[ 1 ]用于写。
一个pipe是单向数据传输的,不用用于父子进程双向读写。创建2个pipe实现父子进程间的双线读写。
#include <unistd.h>
#include <stdio.h>
#include <wait.h>
int main() {
int fds1[2];
int fds2[2];
// fds[0]用于读,fd[1]用于写
// 这里创建2个pipe
pipe(fds1);
pipe(fds2);
printf("fds1: %d, %d\n", fds1[0], fds1[1]);
printf("fds2: %d, %d\n", fds2[0], fds2[1]);
// 创建子进程
pid_t pid = fork();
if (pid > 0) {
// 父进程
// 关闭2个pipe中不需要的文件描述符
close(fds1[0]);
close(fds2[1]);
printf("parent: %d: parent process (child: %d)\n", getpid(), pid);
char s[128];
sprintf(s, "from parent(%d), to child(%d)", getpid(), pid);
write(fds1[1], s, sizeof(s));
char buf2[80];
read(fds2[0], buf2, sizeof(buf2));
printf("parent: receive: %s\n", buf2);
close(fds1[1]);
close(fds2[0]);
} else if(pid == 0) {
// 子进程
// 关闭2个pipe中不需要的文件描述符
close(fds1[1]);
close(fds2[0]);
printf("child: %d: child process, parent(%d)\n", getpid(), getppid());
char buf1[80];
read(fds1[0], buf1, sizeof(buf1));
printf("child: receive: %s\n", buf1);
char s[128];
sprintf(s, "to parent(%d), from child(%d)", getppid(), getpid());
write(fds2[1], s, sizeof(s) );
close(fds1[0]);
close(fds2[1]);
}
waitpid(pid, NULL, 0);
return 0;
}