【发布时间】:2018-03-22 20:37:05
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
FILE *file;
file = fopen(argv[1], "r");
char buf[600];
char *pos;
pid_t parent = fork();
if(parent == 0) {
while (fgets(buf, sizeof(buf), file)) {
pid_t child = fork();
if(child == 0) {
/* is there a function I can put here so that it waits
once the parent is exited to then run?*/
printf("%s\n", buf);
return(0);
}
}
return(0);
}
wait(NULL);
return(0);
}
这里的目标是同时并行打印出文件的行。
例如:
给定一个文件
a
b
c
$ gcc -Wall above.c
$ ./a.out file
a
c
b
$ ./a.out file
b
c
a
就像在同一时间运行的进程一样。我想如果有一个等待父项退出然后开始运行子项的等待子句,我可以让它工作。如上面的 cmets 所示。一旦父进程退出,所有进程都会根据需要从 print 语句开始。
【问题讨论】:
-
我认为我们对“在同一时间”有不同的理解。请解释一下。
-
它们并行运行,行的顺序无关紧要,每行都是独立的。
-
也许 threads 更适合您的目的。您必须使用流程吗?
-
是只使用 fork 的进程
-
这篇文章似乎回答了你的问题。 stackoverflow.com/questions/32723398/…