Search code examples
cprocessfork

fork() returns positive number instead of zero


I'm having an issue of understanding why fork() returns positive number instead of zero when i use it only once in the code.i have been searching for a solution for few hours but nothing helped me. this is the code

#include <stdio.h>
#include <stdlib.h> //for exit
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h> //for sleep(),execvp()
#include <ctype.h>
#include <fcntl.h>
#define IN 0
#define OUT 1
#define SIZE 9
    int main(int argc, char * argv[]) {
        int pipe_descs[2];
        int matrix[SIZE][SIZE];
        int fdr, fdw;   // file descriptors
        int i;
           int status=0;
        /*if (pipe(pipe_descs) == -1) {
            fprintf(stderr, "cannot open");
            exit(1);
        }*/
                fdr = open(argv[1], O_RDONLY);   // open files
                fdw = open("gg.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
             if (fdr < 0 || fdw < 0) { //validation for error
                 perror("failed to open input or output files");
                 exit(EXIT_FAILURE);
             }
            removeSpaces(matrix, fdr, fdw);
             status=fork();
            if (status < 0) {
                fputs("error in fork", stderr);
                exit(EXIT_FAILURE);
            }
             if(status == 0) {
                    printf("got to child"); 
                    dup2(pipe_descs[IN],0);
                    close(pipe_descs[IN]);
                    dup2(pipe_descs[OUT],4);
                    close(STDOUT_FILENO);


            }

        close(fdr);   // close the files
        close(fdw);
        exit(EXIT_SUCCESS);
    }

Solution

  • By the time fork() returns, you have two (almost) identical processes running - the parent and the child. As if you ran your program twice.

    The parent process gets a positive return from the fork() - the PID of the child process. The child gets a zero.

    The line "got to child" is not printed because printf buffers the output until the newline character is printed, and you close the stdout handle before it gets a chance to flush the buffer. Either insert a \n at the end of it, or remove the close(STDOUT_FILENO) line.