建立管道的函數:
#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通訊