Why does forking my process cause the file to be read infinitely

后端 未结 4 1330
小蘑菇
小蘑菇 2020-11-29 12:08

I\'ve boiled down my entire program to a short main that replicates the issue, so forgive me for it not making any sense.

input.txt is a text file that has a couple

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 12:57

    The exit() call closes all open file handles. After the fork, the child and parent have identical copies of the execution stack, including the FileHandle pointer. When the child exits, it closes the file and resets the pointer.

      int main(){
            freopen("input.txt", "r", stdin);
            char s[MAX];
            prompt(s);
            int i = 0;
            char* ret = fgets(s, MAX, stdin);
            while (ret != NULL) {
                //Commenting out this region fixes the issue
                int status;
                pid_t pid = fork();   // At this point both processes has a copy of the filehandle
                if (pid == 0) {
                    exit(0);          // At this point the child closes the filehandle
                } else {
                    waitpid(pid, &status, 0);
                }
                //End region
                printf("%s", s);
                ret = fgets(s, MAX, stdin);
            }
        }
    

提交回复
热议问题