网站的导航栏设计文本,公司部门聚餐计入什么科目,网站如何做网络推广,做书的网站有哪些内容Linux系统调用pipe函数#xff0c;创建一个pipe#xff0c;通过传入的fd数组返回pipe的读、写两端。 其中fd[ 0 ]用于读#xff0c;fd[ 1 ]用于写。 一个pipe是单向数据传输的#xff0c;不用用于父子进程双向读写。创建2个pipe实现父子进程间的双线读写。
#include u…Linux系统调用pipe函数创建一个pipe通过传入的fd数组返回pipe的读、写两端。 其中fd[ 0 ]用于读fd[ 1 ]用于写。 一个pipe是单向数据传输的不用用于父子进程双向读写。创建2个pipe实现父子进程间的双线读写。
#include unistd.h
#include stdio.h
#include wait.hint main() {int fds1[2];int fds2[2];// fds[0]用于读fd[1]用于写// 这里创建2个pipepipe(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;
}