目标是为文件中的每个单词创建一个子进程,并让子进程打印该单词。该文件只有以下五个单词,每个单词占一行:
Aachen
Biscay
Capri
Dino
Ellis
问题是,当我尝试打印到文件时,其中一个单词打印了两次。
Aachen
Ellis
Biscay
Capri
Ellis
Dino
这是代码。这看起来很简单,但我不明白为什么我会得到额外的词。
int main (int argc, char *argv[])
{
char word[50];
int i;
pid_t p;
while (fscanf(stdin, "%s", word) != EOF) {
i = 0;
while (i < sizeof(word)) {
if (word[i] < 'A' || word[i] > 'z') {
word[i] = '\0';
break;
}
i++;
}
p = fork();
if (p != 0)
continue;
break;
}
fprintf(stdout, "%s\n", word);
return 0;
}
我运行程序如下:
$ ./printwords
最佳答案
父亲也在最后打印最后一个字。尝试这个而不是在循环之后打印:
if (p == 0) {
fprintf(stdout, "%s\n", word);
}
else {
continue;
}
关于c - 尝试使用 C 子进程打印文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451827/