在一个文件中,我想“高效地”使用大量单词(10.000个),因此我决定将它们分成100个单词的块,并在最大数量的孩子中分配流程(8)以避免开销,但是我用于读取文件的 while 语句不会变为false。这是我的代码,没有适当的导入:
FILE* fp = fopen(argv[1], "r");
int index= 0;
int childs_amount = 0;
char* word = malloc(sizeof(char) * 46); /* 45 is the len of the largest word in english */
char** words = malloc(sizeof(char*) * 100); /* 100 is the amount of words I want to assign to a child */
while(fscanf(fp, "%s", word) == 1) {
words[index] = malloc(sizeof(char) * 46);
strcpy(words[index], word);
index++;
if (index == 100) {
index = 0;
pid_t child_pid = fork();
if (child_pid == 0) { /* Child process */
usleep(5000); /* do something */
exit(0);
} else { /* Parent Process */
childs_amount++;
if (childs_amount == 8) { /* 8 is the max amount of childs I want at the same time */
pid_t ended_pid = wait(&status); /* wait for any process to finish */
childs_amount--;
}
}
}
}
fclose(fp);
这就像我的子进程正在访问它,或者我应该在每次 exit(0)之前关闭文件,但是我真的不知道,请帮忙。