一.管道
1.可有多個進程向一個進程寫入資料,讀入資料的進程只能有一個
2.管道通訊只能支援單向通訊,如果實現雙向通訊效果,則需要建立兩個管道
3.管道只支援有父子關係和有共同父進程關係的子進程之間的進程通訊
int pipe(int filedes[2]);
功能:filedes 為兩個元素的整型數組,pipe 調用產生一個管
道,管道的讀描述符存入filedes[0],管道的寫描述符存入
filedes[1]。一個進程可以向filedes[1]中寫入資料,另一個進程
可以從filedes[0]中讀出資料。
代碼舉例如下:
/* * piperw.c - The correct way to open a pipe and fork * a child process. */#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <limits.h>#define BUFSZ PIPE_BUFvoid err_quit(char *msg);int main(int argc, char *argv[]){int fd[2]; /* File descriptor array for the pipe */int fdin; /* Descriptor for input file */char buf[BUFSZ];int pid, len;/* Create the pipe */if((pipe(fd)) < 0)err_quit("pipe"); /* Fork and close the appropriate descriptors */if((pid = fork()) < 0)err_quit("fork");if (pid == 0) {/* Child is reader, close the write descriptor */close(fd[1]);while((len = read(fd[0], buf, BUFSZ)) > 0)write(STDOUT_FILENO, buf, len);close(fd[0]);} else {/* Parent is writer, close the read descriptor */close(fd[0]);if((fdin = open(argv[1], O_RDONLY)) < 0) { perror("open"); /* Send something since we couldn't open the input */ write(fd[1], "123\n", 4); } else { while((len = read(fdin, buf, BUFSZ)) > 0) write(fd[1], buf, len); close(fdin); } /* Close the write descriptor */ close(fd[1]); } waitpid(pid, NULL, 0);exit(EXIT_SUCCESS);} void err_quit(char *msg){perror(msg);exit(EXIT_FAILURE);}
二,FIFO(具名管道)
因為以上提到的管道只支援父子進程或有相同父進程之間的子進程之間的進程通訊,故而為了實現非此關係外的進程通訊,FIFO油然而生,他通過一個檔案寫入讀取實現管道通訊。
/* * rdfifo.c - Create a FIFO and read from it */#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <limits.h>int main(void){int fd;/* Descriptor for FIFO */int len; /* Bytes read from FIFO */char buf[PIPE_BUF];mode_t mode = 0666;if((mkfifo("fifo1", mode)) < 0) {perror("mkfifo");exit(EXIT_FAILURE);} /* Open the FIFO read-only */ if((fd = open("fifo1", O_RDONLY)) < 0) { perror("open"); exit(EXIT_FAILURE); } /* Read and display the FIFO's output until EOF */ while((len = read(fd, buf, PIPE_BUF - 1)) > 0) printf("rdfifo read: %s", buf); close(fd); exit(EXIT_SUCCESS);}