当前位置:文档之家› Linux环境编程8进程间通信

Linux环境编程8进程间通信


在写管道时,已写但尚未被读走的字节数应小于或等于PIPE_BUF(4096B).
4
8.2 管道
pipe函数
22 23 cpid = fork();
示例[8-12e4x_pifi(pcepi.dc]== -1) {
/* create child process */
25
perror("fork");
8{
34
9 int pipefd[2];
35
write(STDOUT_FILENO, "\n", 1);
10 pid_t cpid;
36
close(pipefd[0]);
11 char buf;
37
exit(EXIT_SUCCESS);
12ቤተ መጻሕፍቲ ባይዱ
38 } else {
/* write argv[1] to pipe in prarent */
fork之后有两个操作选择,这取决于所需建立的管道的数据流向。根据不同 流向,在父子进程中要关闭相应端口。
在通信过程中的读、写规则:
当读一个写端已被关闭的管道时,在所有数据都被读取后,read返回0,以指 示到了文件结束处。
如果写一个读端已被关闭的管道,则产生SIGPIPE信号。如果忽略该信号或者 捕获该信号并从其处理程序返回,则write出错返回,errno设置为EPIPE。
第8章
进程间通信
1
8.2 管道
父进程
子进程
父进程
子进程
pipe函数
fd[0] fd[1]
fd[0] fd[1]
可通过调用pipe函数来创建一个管道。
fd[1]
fd[0]
#include <unistd.h> 管道
管道
int pipe(int filedes[2]);
filedes
用于返回内文核 件描述符的数组。
Program268-1 exe_xpiitp(Ee.XcIT_FAILURE);
1 #include <sys/wait.h>27 }
2 #include <stdio.h> 28
3 #include <stdlib.h> 29 if (cpid == 0) {
/* read pipe in child */
command
将在子进程中执行的命令行字符串。
type
打开方式,应为"r"或"w"二者之一,含义与fopen的第 二个参数一样。
返回值
成功时,popen返回一个文件流指针,pclose返回command的终止状态。 出错时,popen返回NULL,pclose返回-1。
说明
函数popen先调用fork函数创建子进程,然后调用exec函数以执行 command,最后返回一个标准I/O文件指针。
内核
返回值
成功时返回0; 出错时返回-1,并设置errno变量。
说明
filedes[0]为读而打开,filedes[1]为写而打开。filedes[1] 的输出将作为 filedes[0]的输入。写入写端的数据将被内核缓存,直到从读端读出。
通常,调用pipe函数的进程会接着调用fork,以创建一个父进程与子进程之 间的IPC通道。
5
8.2 管道
popen和pcolse函数
这两函数用于实现:创建管道,fork子进程,然后关闭管道的不使用端, 在子进程中exec一个shell以执行一条命令,然后等待命令的终止。
#include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream);
popen打开的文件流是全缓存的。
函数pclose关闭标准I/O流,并等待command命令执行结束,最后返回shell 的终止状态。
popen函数执行command的方式同system()函数,相当于在Shell下执行: “sh –c command”。
6
8.2 管道 Program 8-2 ex_popen.c 1 #include <sys/wait.h>
18 if (pipe(pipjieafndg) l=in=m4-e14i)@{u}b/u*nctrue:a~te/cp$ipegc*c/ -o ex_pipe ex_pipe.c
19 20 21
} pexeirtr(oErX(jt"IihpTai_inpsFegAi"slI)iLn;aUmR4seE5tri)@i};nugbfuronmtu:f~at/hce$r./ex_pipe "this is a string from father"
15
exit(EXIT_FAILUR4E1); close(pipefd[1]); /* close write end, so EOF will be read */
16 }
42
wait(NULL);
/* wait the exit of child */
17
43
exit(EXIT_SUCCESS);
2 #include <stdio.h>
pop示en例和[8p-c2oles345xe_#in函_itnpm数clouapdinee(vn<o_sitdfd)illitbe.hr.>c & 8-3 ex_popen.c]
6{
Program 8-2 ex_pope7n_filcthera.rc line[BUFSIZ];
1 #include <ctype.h>
8 FILE* fpRead;
2 #include <stdio.h>
13 if (argc != 2) { 39
close(pipefd[0]); /* close read end */
14
fprintf(stderr, "Us4a0ge: %sw<ristetr(ipnigp>ef\dn["1, ]a,ragrvg[v0[]1);], strlen(argv[1]));
4 #include <unistd.h> 30
close(pipefd[1]); /* close write end */
5 #include <string.h> 31
6
32
while (read(pipefd[0], &buf, 1) > 0)
7 int main(int argc, char 3*3argv[]) write(STDOUT_FILENO, &buf, 1);
相关主题