linux 處理序間通訊之管道和FIFO

來源:互聯網
上載者:User

一.管道

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);}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.