I am reading "Operating System: Three Easy Pieces". In chapter 5, there is a piece of code that show the usage of exec() system call.
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
Why is strdup() used in line 12~14 ? I've tried to replace this part with the following:
12 myargs[0] = "wc";
13 myargs[1] = "p3.c";
14 myargs[2] = NULL;
It works just as the previous one.