Process creation and termination in OS

Share

Using the fork() system call, new processes can be started. The process that initiated it (or the process when execution began) is referred to as the parent process, and the newly established process is referred to as the child process. We now have two processes, a parent and child process, resulting from the fork() system function.

The three values that the fork() system call can return are:

  • A negative value denotes an error, or the failure to successfully create the child process.
  • zero is returned for a child process.
  • A positive value: This value represents the freshly generated child process’s process ID.

A process may end in any of the following two ways:

  • Upon the delivery of specific signals, such as a terminate signal, an anomaly develops.
  • Normally, utilizing the exit() library function or the _exit() system call.

The cleanup action is where _exit() and exit() vary most. The _exit() (or _Exit()) would relinquish control to the kernel instantly as opposed to the exit(), which performs cleanup before doing so.

Here is a C program for demonstrating process creation and termination in an operating system

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
   pid_t pid, child_pid, child_ppid;
   pid = getpid();
   printf("+ Process id : %d\n", pid);
   pid = fork();

   if (pid < 0) {
      perror("x fork() failure\n");
      return 1;
   }

   // Child process
   if (pid == 0) {
      printf("- This is child process\n");
      child_pid = getpid();
      child_ppid = getppid();
      printf("+ Process id: %d \t PPID: %d\n", child_pid, child_ppid);
   } else { // Parent process 
      sleep(2);
      printf("+ Parent process \n");
      child_pid = getpid();
      child_ppid = getppid();
      printf("+ Process id: %d \t PPID: %d\n", child_pid, child_ppid);
      printf("+ Newly created process/Child pid :  %d\n", pid);
   }
  
  
   _exit(0); //termination
    printf("Terminating process %d \n",pid);
   return 0;
}
Parent and child process

Source code: https://github.com/CodewithSudeep/operating-system-c-program

Other C Programs: https://codewithsudeep.com/category/c-program/

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: