本章将说明进程之间相互通信的其它技术----进程间通信(IPC)

 

 

管道

管道只能在具有公共祖先的两个进程之间只用。通常,一个管道由一个进程创建,在进程调用fork后,这个管道就能在父进程和子进程之间使用了。

管道是通过调用pipe函数创建的:

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

经由参数fd返回两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。fd[1]是输出,fd[0]是输入。

下图演示从父进程到子进程的管道(父进程关闭管道的读端(fd[0]),子进程关闭管道的写端(fd[1]))

apue学习笔记(第十五章 进程间通信)

 

下面程序创建了一个父进程到子进程的管道,并且父进程经由该管道向子进程传送数据

 1 #include "apue.h"
 2 
 3 int
 4 main(void)
 5 {
 6     int        n;
 7     int        fd[2];
 8     pid_t    pid;
 9     char    line[MAXLINE];
10 
11     if (pipe(fd) < 0)
12         err_sys("pipe error");
13     if ((pid = fork()) < 0) {
14         err_sys("fork error");
15     } else if (pid > 0) {        /* parent */
16         close(fd[0]);
17         write(fd[1], "hello world\n", 12);
18     } else {                    /* child */
19         close(fd[1]);
20         n = read(fd[0], line, MAXLINE);
21         write(STDOUT_FILENO, line, n);
22     }
23     exit(0);
24 }
View Code

相关文章: