无名pipe用在父子进程通信。
以下通过fork创建了一个子进程。
一个pipe有2个fd,其中fd[0]用来读,fd[1]用来写入。
以下演示子进程写入,父进程读取写入的值。
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[]) {
int pipefd[2];
// pipefd[0] for read
//pipefd[1] for write
pid_t cpid;
char buf;
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
char *a = "123456";
write(pipefd[1], a, strlen(a));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
printf("parent end");
exit(EXIT_SUCCESS);
}
}