How to create a process in Linux?


A program loaded into memory and executing is called a process. In simple, a process is a program in execution.

Let’s inspect how to create a process in Linux

A new process can be created by the fork() system call. The new process consists of a copy of the address space of the original process. fork() creates new process from existing process. Existing process is called the parent process and the process is created newly is called child process. The function is called from parent process. Both the parent and the child processes continue execution at the instruction after the fork(), the return code for the fork() is zero for the new process, whereas the process identifier of the child is returned to the parent.

Fork() system call is situated in <sys/types.h> library.

System call getpid() returns the Process ID of the current process and getppid() returns the process ID of the current process’s parent process.

Example

Let’s take an example how to create child process using fork() system call.

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
int main( ){
   pid_t child_pid;
   child_pid = fork (); // Create a new child process;
   if (child_pid < 0) {
      printf("fork failed");
      return 1;
   } else if (child_pid == 0) {
      printf ("child process successfully created!
");       printf ("child_PID = %d,parent_PID = %d
",       getpid(), getppid( ) );    } else {       wait(NULL);       printf ("parent process successfully created!
");       printf ("child_PID = %d, parent_PID = %d", getpid( ), getppid( ) );    }    return 0; }

Output

child process successfully created!
child_PID = 31497, parent_PID = 31496
parent process successfully created!
child_PID = 31496, parent_PID = 31491

Here, getppid() in the child process returns the same value as getpid() in the parent process.

pid_t is a data type which represents the process ID. It is created for process identification. Each process has a unique ID number. Next, we call the system call fork() which will create a new process from calling process. Parent process is the calling function and a new process is a child process. The system call fork() is returns zero or positive value if the process is successfully created.

Updated on: 31-Jan-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements