linux的套介面和管道

來源:互聯網
上載者:User

  建立管道的函數:

#include <unistd.h>int pipe(int pipefd[2]);

  pipefd[0]代表管道讀出端的檔案描述符,pipefd[1]代表管道寫入端的檔案描述符。資訊只能從pipefd[0]讀出,也只能重pipefd[1]寫進。所以實現的通訊就是單項的,如果要實現雙向通訊的話可以採用建立兩個管道。不過也可以使用通訊端通訊。因為通訊端的通訊是雙向的。

  建立管道的例子:

#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>intmain(int argc, char *argv[]){    int pipefd[2];    pid_t cpid;    char buf;    if (argc != 2) {      fprintf(stderr, "Usage: %s <string>\n", argv[0]);      exit(EXIT_FAILURE);    }    if (pipe(pipefd) == -1) {        perror("pipe");        exit(EXIT_FAILURE);    }    cpid = fork();    if (cpid == -1) {        perror("fork");        exit(EXIT_FAILURE);    }    if (cpid == 0) {    /* 子進程從管道中讀取 */           close(pipefd[1]);          /* 讀的時候先關閉不用的寫進端 */        while (read(pipefd[0], &buf, 1) > 0)            write(STDOUT_FILENO, &buf, 1);        write(STDOUT_FILENO, "\n", 1);        close(pipefd[0]);        _exit(EXIT_SUCCESS);    } else {            /* 父進程向管道寫入 argv[1]*/        close(pipefd[0]);          /* 寫之前關閉不用的讀出端*/        write(pipefd[1], argv[1], strlen(argv[1]));        close(pipefd[1]);          /* Reader will see EOF */        wait(NULL);                /* Wait for child */        exit(EXIT_SUCCESS);    }}

  

  建立套介面的函數:

#include <sys/types.h> #include <sys/socket.h>int socketpair(int domain, int type, int protocolint " sv [2]);

  sv[2]是指向接收用於引用套介面檔案描述符數組的指標。類似於管道中的端點。使用例子:

 

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>int main(){    int z;    int s[2];        z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);    if (z==-1)    {        fprintf(stderr,"%s:socketpair(AF_LOCAL,SOCK_STREAM,0)\n",strerror(errno));        exit(1);    }    printf("s[0]=%d;\n",s[0]);    printf("s[1]=%d;\n",s[1]);    return 1;    }

   下一篇:套介面和I/O通訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.