一、管道讀寫注意點
1.只有在管道讀端存在時,向管道寫入才有意義;否則,會收到核心中的出錯訊號:SIFPIPE
2.向管道寫入資料時不保證寫入的原子性,管道緩衝區一有空閑地區,寫進程就試圖向其寫入內容。若讀進程不讀取管道中的內容,則寫進程會一直阻塞。
3.父子進程在運行時,它們的先後順序得不到保證。因此在這裡,為保證父進程關閉讀描述符,可向子進程加入sleep(2)。
二、執行個體
1.無名管道
/*pipe_rw.c*/#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>int main(){int pipe_fd[2];pid_t pid;char buf_r[100];char* p_wbuf;int r_num;memset(buf_r,0,sizeof(buf_r));if(pipe(pipe_fd)<0){printf("pipe create error\n");return -1;}if((pid=fork())==0) //若是子進程{printf("\n");/*關閉子進程管道寫端。睡眠2秒,確保父進程已相應地關閉了管道讀端*/close(pipe_fd[1]);sleep(2);/*子進程讀取管道內容*/if((r_num=read(pipe_fd[0],buf_r,100))>0){printf( "%d numbers read from the pipe is %s\n",r_num,buf_r);}/*關閉子進程讀端*/close(pipe_fd[0]);exit(0); }else if(pid>0){/*關閉父進程讀端*/close(pipe_fd[0]);/*分兩次向管道寫入資料*/if(write(pipe_fd[1],"Hello",5)!=-1)printf("parent write1 success!\n");if(write(pipe_fd[1]," Pipe",5)!=-1)printf("parent write2 success!\n");/*關閉父進程寫端並睡眠3秒,讓子進程讀資料*/close(pipe_fd[1]);sleep(3);/*收集子進程退出資訊*/waitpid(pid,NULL,0);exit(0);}}運行結果如下:
[root@localhost ipc]# ./pipe_rwparent write1 success!parent write2 success!10 numbers read from the pipe is Hello Pipe
2.有名管道
/*fifo_write.c*/#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO_SERVER "/tmp/myfifo"main(int argc,char** argv){int fd;char w_buf[100];int nwrite;if(fd==-1)if(errno==ENXIO)printf("open error; no reading process\n");/*開啟有名管道,並設定為非阻塞*/fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);if(argc==1)printf("Please send something\n");strcpy(w_buf,argv[1]);/*向管道寫入字串*/if((nwrite=write(fd,w_buf,100))==-1){if(errno==EAGAIN)printf("The FIFO has not been read yet.Please try later\n");}else printf("write %s to the FIFO\n",w_buf);}/*fifo_read.c*/#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO "/tmp/myfifo"main(int argc,char** argv){char buf_r[100];int fd;int nread;/*建立有名管道,並設定相應的許可權*/if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))printf("cannot create fifoserver\n");printf("Preparing for reading bytes...\n");memset(buf_r,0,sizeof(buf_r));/*開啟有名管道,並設定非阻塞標誌*/fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);if(fd==-1){perror("open");exit(1);}while(1){memset(buf_r,0,sizeof(buf_r));/*讀取管道中的字串*/if((nread=read(fd,buf_r,100))==-1){if(errno==EAGAIN)printf("no data yet\n");}printf("read %s from FIFO\n",buf_r);sleep(1);}pause();unlink(FIFO);}運行結果:
終端1:
[root@localhost ipc]# ./fifo_write 123123write 123123 to the FIFO
終端2:
[root@localhost ipc]# ./fifo_readPreparing for reading bytes...read from FIFOread from FIFOread from FIFOread from FIFOread from FIFOread 123123 from FIFOread from FIFO