具體參考:https://blog.csdn.net/sdkdlwk/article/details/79765676數組
//建立有名管道(FIFO special file),建立完了就像普通文件同樣open(),再讀寫,成描述符功返回0,失敗返回-1設errno。VS$man 3 mkfifo #include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode);
pathname:the FIFO special file's namespa
mode :the FIFO's permissions..net
//建立FIFO管道文件
int res=mkfifo(「./a.fifo」,0664); if(-1==res) perror("mkfifo"),exit(-1); res=open(「./a.fifo」,O_RDONLY); if(-1==res) perror(「open」),exit(-1);
//建立無名管道,至關於直接把open()返回的fd直接放到形參中,而不需額外的變量接收管道文件的描述符,用於父子進程間經過管道進行IPC通訊,,成功返回0,失敗返回-1設errno #include <unistd.h> int pipe(int pipefd[2]); //代碼自注釋,表示它須要的參數是一個有兩個元素的數組,若是雖然做爲形參,實質上和int* pipefd沒有區別
pipefd :return two fds referring to the ends of the pipe.code
fork()建立的child也會文件描述符總表也會複製一份So,對於child, 應該先關閉讀端, 再寫,對於parent,應該先關閉寫端, 再讀regexp
//使用pipe()實現父子進程的通訊 #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h> #include<stdio.h> int main(){ //1. 建立無名管道 int pipefd[2]; int res=pipe(pipefd); if(-1==res) perror("pipe"),exit(-1); //2. 建立子進程 pid_t pid=fork(); if(-1==pid) perror("fork"),exit(-1); //3. 子進程開始啓動,寫入1~100; if(0==pid){ close(pipefd[0]); int i=0; for(i=1;i<=100;i++){ write(pipefd[1],&i,sizeof(int)); } close(pipefd[1]);//關閉寫端 exit(0); } //4. 父進程開始啓動,讀取管道中的數據 close(pipefd[1]); int i=0; for(i=1;i<=100;i++){ int x=0; read(pipefd[0],&x,sizeof(int)); printf("%d ",x); } printf("\n"); close(pipefd[0]); return 0; }