管道:當從一個進程串連資料流到另一個進程時,使用術語管道(pipe)。
#i nclude <unistd.h>
int pipe(int filedes[2]); //建立管道
pipe()說明:
傳回值:0成功,-1出錯。
如果調用成功,則進程此時由了兩個額外的開啟檔案描述符,filedes[0]中的值是管道的讀取端,而filedes[1]是管道的寫入端。
#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");
//關閉管道寫描述符,進行管道讀操作
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");
close(pipe_fd[1]);
sleep(3);
waitpid(pid,NULL,0);
exit(0);
}
}
管道讀寫注意事項:
1.必須在系統調用fork()中調用pipe(),否則子進程將不會繼承檔案描述符;
2.當使用半雙工管道時,任何關聯的進程都必須共用一個相關的祖先進程。