Search code examples
cforkfopenfgetspid

Keep getting a seg fault when trying to open files with child and parent processes?


I am trying to open a text file and have both a child and parent process read from the file one line at a time and output their PID followed by the line that was read. Except no matter what I seem to do I keep getting a seg fault and can't even locate where my problem is.

int main(int argc, char *argv[]){

    if(!argv[1]){
             return 1;
    }

    int var1 = strtol(argv[1], NULL, 10);

    FILE *fp;
    fp = fopen("prog2Boutput.txt", "r");

    if (fp == NULL) {
            fprintf(stderr, "Can't open input file in.list!\n");
            exit(1);
    }

    int childP = fork();

    if(childP<0){
            fprintf(stderr, "fork failed\n");
            exit(1);
    }
    else if(childP==0){
            char* line = fgets(line,150, fp);
            printf("child: (pid:%d) (line:%s)\n", (int)getpid(), line);
    }
    else{
            char* line = fgets(line,150,fp);
            printf("parent: (pid:%d) (line:%s)\n", (int)getpid(), line);
    }

    fclose(fp);
    return 0;
}

Solution

  • You might have two errors:

    1. You're using strtol() without checking that there's an argv[1]. You should put in a guard.
    2. You aren't using fgets() correctly. The first argument must be a buffer that you allocate yourself, as in:

      char line[200];
      char *cp = fgets(line, 150, fp);
      

    After that cp will be either 0 (when fgets() couldn't read anything) or it will point to the first character of line.

    (Last, as point of style, main() should return an int, not void. Some modern compilers won't accept your code.)