Linux C Programming learning-process, process, process !, Linux Programming
Linux supports multiple processes at the same time, that is, the multi-Program Design in the modern operating system, which is also called scheduling each process in the linux system to occupy the cpu time. Since the time of each time slice is very small compared with the macro time, it gives people the feeling that multiple processes are running. To improve the program running efficiency, the program is often divided into multiple parts, that is, the concurrent program design. Processes in a concurrent program are independent of each other and communicate with each other through corresponding mechanisms when necessary. If resources are to be shared among processes, in order to avoid conflicts, resources are usually used in turn through the corresponding communication mechanism. When a process is communicating, a process may wait for another process to continue running. This also requires inter-process communication to understand the running status of the other process. Sometimes mutual exclusion occurs between processes, which uses the lock mechanism. In the concurrent program design, Process Creation and termination are determined by the user. This introduces the concept of parent and child processes.
Process Creation:
1 #include <unistd.h> 2 3 pid_t fork(void); 4 pid_t vfork(void);
In this summary, the child process created by fork is a copy of the parent process, but it uses different data segments and stacks than the parent process. Vfork and fork are basically the same, but vfork does not copy the data segment of the parent process. They share the data segment. This is because vfork and the exec function often call a program such as the ls command to start a new process. After vfork, the parent process waits for the child process to finish running or calls exit. The running sequence of the fork parent process and child process is uncertain.
The procedures that reflect their nature are as follows:
1 #include <sys/types.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 6 main() 7 { 8 pid_tpid; 9 char*pchar = "before fork"; 10 inttest_va = 1; 11 12 if((pid= fork()) < 0 ) 13 { 14 printf("forkerror!!\n"); 15 exit(1); 16 } 17 18 elseif(pid == 0) 19 { 20 printf("childprocess\n"); 21 pchar= "child pchr\n"; 22 printf("%s\n",pchar); 23 24 test_va= 2; 25 26 printf("%d\n",test_va); 27 _exit(2); 28 } 29 30 else 31 { 32 printf("parentprocess\n"); 33 printf("%s\n",pchar); 34 printf("%d\n",test_va); 35 } 36 }
Fork:
Vfork: