Fork
Fork
fork()
The fork system call is used for creating a new process in Unix/Linux. The child process created by
the process that makes the fork() call. After child process creation, both parent and child process
executes the next instruction.
The child process uses the same Program counter(PC), same CPU registers, and same open files
which use in the parent process.
fork() will not take any arguments but return integer.
Syntax:
#include <unistd.h>
pid_t fork(void);
Return Values:
• Negative Value : The creation of child process is unsuccessful.
• Zero : Returned to the newly created child process.
• Positive Value : Returned to the parent or Caller. The value contains the process ID of the
newly created child process.
getpid() :
getpid() is used to retrive the process ID(PID) of the calling process.
Syntax:
#include <sys/types.h>
#include <unistd.h>
pid_t getpid(void);
Return Values:
• The return value of getpid() is of type pid_t, which is a signed integer type. It
represents the PID of the calling process.
Example 1: Demonstration of getpid()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t my_pid;
my_pid = getpid();
printf("My process ID is: %d\n", my_pid);
return 0;
}
waitpid() :
waitpid() is used to wait for specific child process to terminate and retrieve its termination
status.
Syntax:
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);
Arguments:
• pid : The PID of the child process you want to wait for. It can have the following special
values:
• -1 : wait for any child process
• 0: wait for any child process in the same process group as the caller.
• >0 : wait for the child process with specified PID.
• status : A pointer to an integer where the exit status of the child process will be stored.
• options : Additional options that control the behavior of the waitpid() function. Common
options include WNOHANG (non-blocking), WUNTRACED (report stopped processes), etc.
Reutrn Values: The return value of waitpid() is the PID of the terminated child process if
successful, or -1 if an error occurred.
WIFEXITED :
Query status to see if a child process ended normally.
This macro queries the child termination status provided by the wait and waitpid functions, and
determines whether the child process ended normally.
Syntax:
#include <sys/wait.h>
int WIFEXITED(int status);
status : The status field that was filled in by the wait or waitpid function.
Expected Output: