Fork in C

Previously, we get Process ID or PID and Parent process ID using C programming. Now, we will see fork() in C. In Linux, each running task is known as “Process”.

From one process we can create another process. To do this fork() library function will be used. fork() split one process into two processes:- parent process, and child process.

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
  printf("Before Forking\n");
  fork();

  printf("After Forking\n");
  printf("Hello world!\n");
  printf("Linux\n");

  return 0;
}

Output:-

Before Forking
After Forking
Hello world!
Linux
After Forking
Hello world!
Linux

Note that after fork() all statements executed twice, one by the parent process and another by the child process.

Linux internally uses to fork() to create a new child process. There will be a tree-like structure of all the processes running in the memory. The father of all these processes is “init”. To list the all running process use this command,

$ ps -A

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Also Learn

Leave a Comment

Your email address will not be published. Required fields are marked *