Saturday, 19 August 2017

Understanding the execution of if-else block using fork

Here is a brief explanation on how both if/else gets execute in case of forking and piping example. Consider the below example:

#include <stdio.h>
#include <unistd.h>
int main() {
  pid_t pid;
  pid = fork();
  if(pid == 0) {
    printf("Hi Coding-Scripting");
  else {
    printf("Bye.! Coding-Scripting");
  return EXIT_SUCCESS;


Whenever the call to fork() function is made, it replicates the whole code written down below the fork. So, now the two processes are created child process, with PID =0, and parent process with PID = X. So, the child execute the if block and exits, and after that parent executes the else block and exits. In this manner, both the if-else blocks will get execute.

No comments:

Post a Comment