Fork process-related, fork Process
Fork Process Problems
# Include
# Include
# Include
# Include
# Include
Int main (int argc, char * argv []) {pid_t pid; int I = 0; pid = fork (); // create process if (pid <0) {// error perror ("fork");} if (pid = 0) {// sub-process while (1) {printf ("I am son \ n "); sleep (1); I ++; if (3 = I) {// After 3 seconds, kill (getppid (), SIGINT); // give the parent process pid, sending interrupt signal SIGINT }}else if (pid> 0) {// parent process while (1) {printf ("I am father \ n "); sleep (1) ;}} return 0 ;}
Print as follows.
I am fatherI am sonI am fatherI am sonI am sonI am fatherI am sonI am sonI am sonI am sonI am sonI am sonI am sonI am sonI am sonI am sonI am son
Take a look at the most basic fork process program
#include
#include
#include
int main(void){ pid_t pid; printf("init pid is %d \n", getpid()); pid = fork(); if (pid == -1) printf ("error fork"); else if(pid == 0) { //sleep(2); printf("\n this is child, and child pid is %d,father pid is %d \n ", getpid(), getppid()); } else { sleep(2); printf("\n this is father, and child pid is %d,father pid is %d \n", pid,getpid()); } return 0;}
When the sleep function is added to the parent process, the child process stops running and the parent process stops running. Print as follows.
init pid is 7758 this is child, and child pid is 7759,father pid is 7758 this is father, and child pid is 7759,father pid is 7758
Remove the sleep function of the parent process, add sleep to the child process, and print the following.
init pid is 7789 this is father, and child pid is 7790,father pid is 7789 this is child, and child pid is 7790,father pid is 1
We can see from above. The parent process ends first, and the child process becomes an orphan process. The system orphan it to the 1 (init) process, so the process number is changed to 1.
Getpid returns the current process ID, and getppid returns the parent process ID.