pipe()用於在兩個有關係的process(通常是父子或是兄弟process)之間通信 假設有A和B兩個process,pipe()建立之後可以用A讀或寫經由pipe傳送到B的寫或讀
#include <unistd.h>
int pipe(int pipefd[2]);
使用pipefd表示讀或寫,pipefd[0]用於讀,pipefd[1]用於寫
在建立管道之後需要fork出一個process,所以目前有父process及fork出來的子process 接著利用cpid判斷哪個process是父process哪個是子process 當父process的寫端需要使用stdout寫出數據給子process的讀端讀取時,這時需要將父process沒有用到的讀端及子process沒用到的寫端關閉 接著就是在父process使用write,及在子process使用read,即可完成父子process之間的通信
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char* argv[])
{
int pipefd[2];
pid_t cpid;
char buf[128];
int readlen;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
return -1;
}
if (pipe(pipefd) < 0) {
fprintf(stderr, "pipe: %s\n", strerror(errno));
return -1;
}
cpid = fork();
if (cpid < 0) {
fprintf(stderr, "fork: %s\n", strerror(errno));
return -1;
}
if (0 == cpid) { /* 子進程 */
close(pipefd[1]); /* 子進程關閉寫端 */
readlen = read(pipefd[0], buf,
128); //子進程阻塞在讀上,等待父進程寫
if (readlen < 0) {
fprintf(stderr, "read: %s\n", strerror(errno));
return -1;
}
write(STDOUT_FILENO, buf, readlen);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]); //讀完之後關閉讀描述符
return 0;
} else { /* 父進程 */
close(pipefd[0]); /*父進程關閉沒用的讀端 */
sleep(2);
write(pipefd[1], argv[1], strlen(argv[1])); //父進程開始寫
close(pipefd[1]); /* 父進程關閉寫描述符 */
wait(NULL); /* 父進程等待子進程退出,回收子進程資源 */
return 0;
}
}