#include<stdio.h> #include<unistd.h> #include<sys/types.h> main() { intfd[2]; pid_t childpid; pipe(fd); if((childpid=fork())==-1) { perror("fork"); exit(1); } if(childpid==0) { /*Child process closes up in put side of pipe*/ close(fd[0]); } else { /*Parent process closes up out put side of pipe*/ close(fd[1]); }.. }
正如前面提到的,一但创建了管道之后,管道所使用的文件描述符就和正常文件的文件描述符一样了。
#include<stdio.h> #include<unistd.h> #include<sys/types.h> intmain(void) { intfd[2],nbytes; pid_tchildpid; charstring[]="Hello,world! "; charreadbuffer[80]; pipe(fd); if((childpid=fork())==-1) { perror("fork"); exit(1); } if(childpid==0) { /*Child process closes up in put side of pipe*/ close(fd[0]); /*Send"string"through the out put side of pipe*/ write(fd[1],string,strlen(string)); exit(0); } else { /*Parent process closes up out put side of pipe*/ close(fd[1]); /*Readinastringfromthepipe*/ nbytes=read(fd[0],readbuffer,sizeof(readbuffer)); printf("Receivedstring:%s",readbuffer); } return(0); }