Search code examples
cfileprocessfork

fprintf returning null after fork() in c


I am trying to open a file with fopen, fork the current process and make the child process write something on the file; when the child process exits, the parents process should read the file's content, but it reads "null", even if the file has been correctly written. No errors are reported. Here is my code:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(int argc, char *argv[]){
    FILE * sharedFile;
    char *fileContent;
    if((sharedFile = fopen("testFile.txt","w+")) == NULL){
        fprintf(stderr,"Error while opening the file: %s",strerror(errno));
        return 0;
    }
    pid_t pid = fork();
    if(pid == 0){
        //Child
        fprintf(sharedFile,"%s",argv[1]);
        exit(0);
    }
    else{
        //Parent
        wait(NULL);
        if(fscanf(sharedFile,"%s",fileContent) < 0){
            fprintf(stderr,"Error while reading file: %s",strerror(errno));
            return 0;
        }
        fprintf(stdout,"File content: %s",fileContent); //Outputs "File content: (null)"
        fclose(sharedFile);
    }
}

Oddly, if I open again the file in the parent's code after the fork, the output is correct. What could be the problem?


Solution

  • fileContent has not been allocated any space. Perhaps do this

    char fileContent[101];
    
    ...
    
    if (fscanf(sharedFile,"%100s",fileContent) != 1) // Prevent buffer overflows. Should return one when successful.