【发布时间】:2015-10-05 11:45:36
【问题描述】:
我有一个程序,它在循环中创建多个 fork() 之后执行父进程之后的所有子进程。 但相反,父进程在每个子进程终止之前运行。
im childprocess : 18389
parent process done
im childprocess : 18390
parent process done
im childprocess : 18391
parent process done
这是我如何使用 fork() 调用的代码
for (int file = 0; file < files_count; file++) {
pid_t pid = fork();
int file_loc = file + 2;
if (pid == 0) {
// child process
occurrences_in_file(argv[file_loc], argv[1]);
break;
} else if (pid > 0) {
// parent process
parentProcess();
} else {
// fork failed
printf("fork() failed!\n");
return 1;
}
}
.
void occurrences_in_file(const std::string& filename_,
const std::string& pattern_);
void occurrences_in_file(const std::string& filename_,
const std::string& pattern_) {
int my_pid;
cout << "im childprocess : " << my_pid <<endl;
}
.
void parentProcess();
void parentProcess() {
while (true) {
int status;
pid_t done = wait(&status);
if (done == -1) {
if (errno == ECHILD){
cout << "parent process done"<< endl;
break; // no more child processes
}
} else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
std::cerr << "pid " << done << " failed" << endl;
_exit(1);
}
}
}
}
【问题讨论】:
标签: c++ multiprocessing fork