Vfork is used to create a new process, which aims to exec a new program. Both vfork and fork create child processes, but vfork does not completely copy the address space of the parent process to the child process, because the child process will call exec (or exit ), therefore, the address space will not be accessed. Before the child process calls exec or exit, it continues to run in the space of the parent process.
Another difference between vfork and fork is that vfork ensures that sub-processes run first. After the child process calls exec or exit, the parent process can be scheduled to run.
1 #include <stdlib.h> 2 #include <unistd.h> 3 #include <sys/types.h> 4 #include <stdio.h> 5 6 int global = 6; 7 8 int main() 9 {10 int var;11 pid_t pid;12 13 var = 88;14 printf("before vfork\n");15 printf("pid = %d, global = %d, var = %d\n", getpid(), global, var);16 17 if ((pid = vfork()) < 0)18 {19 perror(" failed to vfork()!\n");20 return -1;21 }22 else if (pid == 0)23 {24 printf(" After vfork, and in child process:\n");25 printf(" pid = %d, global = %d, var = %d\n", getpid(), global, var);26 27 global++;28 var++;29 _exit(0);30 }31 32 printf("\n\nAfter vfork, and in parent process:\n");33 printf(" pid = %d, global = %d, var = %d\n", getpid(), global, var);34 35 return 0;36 }
View Code
Running result:
Execute a program using the exec function. When a process calls an exec function, the Program executed by the process is completely replaced with a new process, and the new program is executed from its main function. Without changing the process ID, exec only replaces the body, Data, heap, and stack segments of the current process with a brand new program.
1 /* gcc echoall.c -o echoall */ 2 #include <stdlib.h> 3 #include <stdio.h> 4 5 int main(int argc, char **argv) 6 { 7 int i; 8 char **ptr; 9 extern char **environ;10 11 for (i = 0; i < argc; ++i)12 printf(" argv[%d]: %s\n", i, argv[i]);13 14 exit(0);15 }
View Code
Place the compilation result of the modified program in the/home/Sunday/share/directory.
1 /* execDemo.c */ 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <sys/types.h> 5 6 int main() 7 { 8 pid_t pid; 9 10 if ((pid = fork()) < 0)11 {12 printf(" fork error!\n");13 return -1;14 }15 else if (pid == 0)16 {17 printf(" Now in child process\n");18 printf(" And not leave parent room\n");19 if (execl("/home/sunday/share/echoall", "echoall", "myarg1",20 (char *) 0) < 0)21 {22 printf(" execle failed!\n");23 return -1;24 }25 }26 27 printf(" Now in parent process\n");28 return 0;29 }
View Code
Running result: