我把我的整个程序归结为一个复制问题的简短主题,所以原谅我没有任何意义.
input.txt是一个文本文件,其中包含几行文本.这个简化的程序应该打印这些行.但是,如果调用fork,程序将进入无限循环,在此循环中反复打印文件的内容.
据我所知,我在这个片段中使用它的方式本质上是一个无操作.它分叉,父母在继续之前等待孩子,孩子立即被杀死.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
enum { MAX = 100 };
int main(){
freopen("input.txt", "r", stdin);
char s[MAX];
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();
if (pid == 0) {
exit(0);
} else {
waitpid(pid, &status, 0);
}
//End region
printf("%s", s);
ret = fgets(s, MAX, stdin);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:进一步的调查只会使我的问题变得更加奇怪.如果文件包含<4个空白行或<3行文本,则不会中断.但是,如果不止于此,它会无限循环.
Edit2:如果文件包含3行数字,它将无限循环,但如果它包含3行单词则不会.