我正在阅读《操作系统:三个简单部分》。第5章中有一段代码展示了exec()系统调用的用法。
1 #include "common.h"
2
3 int main(int argc, char ** argv) {
4 printf("hello world (pid: %d)\n", (int) getpid());
5 int rc = fork();
6 if (rc < 0) {
7 fprintf(stderr, "fork failed\n");
8 exit(1);
9 } else if (rc == 0) {
10 printf("hello, I am child (pid: %d)\n", (int) getpid());
11 char *myargs[3];
12 myargs[0] = strdup("wc");
13 myargs[1] = strdup("p3.c");
14 myargs[2] = NULL;
15 execvp(myargs[0], myargs); // run work count
16 printf("this shouldn't print out\n");
17 } else {
18 int wc = wait(NULL);
19 printf("hello, I am parent of %d (wc: %d) (pid: %d)\n", rc, wc, (int) getpid());
20 }
21 return 0;
22 }
23
为什么在第12到14行使用了strdup()函数? 我曾试图将此部分替换为以下内容:
12 myargs[0] = "wc";
13 myargs[1] = "p3.c";
14 myargs[2] = NULL;
它的工作方式与以前的相同。
strdup()
?没有询问他就无法确定。 - user207421exec
函数族如何工作。 - Some programmer dudeexecvp
失败时才会发生泄漏,而在这种情况下,进程无论如何都会退出。 - Nate Eldredge