8.1.7 进程编程实例
在本节的最后,给出一个多进程编程的综合实例,程序会创建两个进程,在父进程和子进程之间通过管道传递数据,父进程向子进程发送字符串exit表示让子进程退出,并且等待子进程返回;子进程查询管道,当从管道读出字符串exit的时候结束。
实例8-7 进程编程实例
1 // process_demo.c
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7
8 int main()
9 {
10 pid_t pid, pid_wait;
11 int fd[2];
12 char buff[64], *cmd = "exit";
13
14 if (pipe(fd)) { // 创建管道
15 perror("Create pipe fail!");
16 return 0;
17 }
18
19 pid = fork();
20 if (-1==pid) {
21 perror("Create process fail!");
22 return 0;
23 } else if (0==pid) { // 子进程
24 close(fd[1]); // 关闭写操作
25 printf("wait command from parent!/n");
26 while(1) {
27 read(fd[0], buff, 64);
28 if (0==strcmp(buff, cmd)) {
29 printf("recv command ok!/n");
30 close(fd[0]);
31 exit(0);
32 }
33 }
34 } else { // 父进程
35 printf("Parent process! child process id: %d/n", pid);
36 close(fd[0]); // 关闭读操作
37 sleep(2);
38 printf("Send command to child process./n");
39 write(fd[1], cmd, strlen(cmd)+1); // 写入命令
40 close(fd[1]);
41 }
42
43 return 0;
44 }
程序第14~17行创建管道,并检查管道创建是否成功。第19行调用fork()函数创建进程。第23~32行是子进程的代码,子进程首先关闭管道写操作,然后进入一个死循环,不断从管道读取数据,如果有数据会检查数据内容,发现字符串exit就调用exit()函数结束进程。第35~40行是父进程的代码,首先是关闭管道读操作,然后等待2秒,向管道写入字符串exit,最后关闭管道写操作。程序运行结果如下:
wait command from parent!
Parent process! child process id: 8013
Send command to child process.
recv command ok!