管道通信属于进程间通信的一种方式,使用方便,但是局限是父进程与子进程间的通信,下面是调试好的代码。
程序父进程创建2个管道,分别用于父进程写数据--子进程读数据和子进程写数据--父进程读数据:
#include <errno.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> int main(int argc,char* argv[]) { int fprcw[2]; //for parent read,child write int fpwcr[2]; char str[256]; pid_t pid; if(pipe(fprcw) == -1) { perror("pipe1"); return -1; } if(pipe(fpwcr) == -1) { perror("pipe2"); close(fprcw[0]); close(fpwcr[0]); return -1; } pid = fork(); if(pid == 0) { close(fprcw[0]); close(fpwcr[1]); sleep(1); write(fprcw[1],"hello world!",12); read(fpwcr[0],str,256); printf("child str is:%s\n",str); close(fpwcr[0]); close(fprcw[1]); } else if(pid > 0) { close(fpwcr[0]); close(fprcw[1]); write(fpwcr[1],"how are you!",12); if(waitpid(pid,NULL,0) == -1) { perror("waitpid"); } read(fprcw[0],str,256); printf("parent str is: %s\n",str); close(fpwcr[1]); close(fprcw[0]); } else { perror("fork"); } return 0; }
时间: 2024-10-02 04:49:52