C Program to show that child inherits parent file descriptors on fork

C Program to show that child inherits parent file descriptors on fork

neelkanth_surekha#cat io_Redirect.c 

#include <stdio.h>
#include <signal.h>
#include <syslog.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{

    int fd = open("/dev/null",0);

   
 /* close STDOUT and STDERR file descriptor so that
     * they can be redirected and the output prints won't
     *  be displayed on the console.
     */

    
/* FOR DISPLAYING THE OUTPUT PRINTS ON THE CONSOLE, 
     * COMMENT OUT THE BELOW 2 LINES  */
    close(STDOUT_FILENO);  //stdout => 1
    close(STDERR_FILENO);  //stderr => 2

    int new_fd;

  
  /* stderr is now redirected */
    new_fd = dup(fd);
    printf("new fd is %d", new_fd);

   
 /* stderr is now redirected */
    new_fd = dup(fd);
    printf("new fd is %d", new_fd);
    close(fd);

    /* NOW, FORK THE CHILD PROCESS. SINCE THE PARENT STDOUT AND STDIN
     * FILE DESCRIPTORS ARE CLOSED, THE CHILD WHICH INHERITS IS FD'S
     * FROM THE PARENT WILL NOT BE ABLE TO PRINT ON THE CONSOLE.
     */
    int pid = fork();

    if (pid == 0)
    {
        printf("\n I am the child \n");
    } else if (pid > 0)
    {
      printf("\n I am the parent\n"); 
    } else {
      perror("fork error"); 
    }

    return 0;
}


Output

neelkanth_surekha#./a.out 
neelkanth_surekha#

<Nothing gets printed here because the stdout and stderr file descriptors are re-directed to /dev/null >