第四章:基于TCP套接字编程(三)

fork and exec and wait

1.fork and wait函数

 1 #include <sys/types.h>
 2 #include <sys/wait.h>
 3 #include <stdlib.h>
 4 #include <unistd.h>
 5 #include <stdio.h>
 6 
 7 
 8 int main(int argc, char *argv[]) {
 9     printf("hello world
");
10     int rc = fork();
11     if (rc < 0) {
12         fprintf(stderr, "fork failed
");
13     } else if (rc == 0) {
14         printf("I am child, rc==%d
", getpid());
15     } else {
16         int wc = wait(NULL);
17         printf("I am parent, pid==(%d), and my child is  (%d), now wait for %d
", getpid(), rc, wc);
18     }
19     return 0;
20 }
21 
22 /*
23 执行结果
24 
25 root@local:/mnt/d/workspace/vscode# ./forkwait
26 hello world
27 I am child, rc==525
28 I am parent, pid==(524), and my child is  (525), now wait for 525
29 
30 */

使用wait,确定父、子进程的调用顺序,wait 的返回值是等待的子进程的pid。

2.fork and exec and wait函数

当你使用 fork 创建了一个子进程的时候,你可能并不想创建一个和父进程的拷贝,想要有自己的”想法“。

 进程与fork()、wait()、exec函数组 - 0x14b7狄 - 博客园 (cnblogs.com)

原文地址:https://www.cnblogs.com/whutao/p/14332298.html