The fork() function creates a new process. The new process (child process) is an exact copy of the calling process (parent process).
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { int childPid; childPid = fork(); printf("YES!\n"); }
getpid() returns the process ID of the calling process
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { int childPid; int pid; childPid = fork(); pid = getpid(); printf("YES! PID:\t%d\n",pid); }
There is no default synchronization between child and parent processes. Consider the example below. In which order do we print the process ids? What would happen without the sleep line? We'll see in the next example how to wait for
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { int childPid; int pid; childPid = fork(); pid = getpid(); if (childPid == 0) { // I'm the child sleep(5); } printf("YES! PID:\t%d\n",pid); }
The man page describes waitpid as follows:
waitpid() suspends the calling process until one of its children changes state; if a child process changed state prior to the call to waitpid(), return is immediate. pid specifies a set of child processes for which status is requested.
We'll use waitpid to suspend the calling parent process until it's child process with process id pid is finished.
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> int main() { int childPid; int pid; int status; childPid = fork(); pid = getpid(); if (childPid == 0) { /* I'm the child */ sleep(5); } else { /* I'm the parent and wait for my child */ waitpid(childPid,&status,0); } printf("YES! PID:\t%d\n",pid); }