好的,所以我一直在努力学习掌握子进程并正确等待它们完成。我已经阅读了很多Stack Overflow Q / A,我似乎仍然无法按照我的意愿使用它。我一直在阅读/搜索这本书(C ++ Primer plus第6版) - 我做了一些研究,但我还是不能让它等到我想要的时候。
所以我在Stack Overflow上看了几件事以供参考:Checking the status of a child process in C++
这是我到目前为止所尝试的内容:
using namespace std;
int main() {
int status;
pid_t child;
child = fork();
if ( child > 0 ) {
cout << "\nChild #1 is in charge\n";
execlp("ls", "ls", NULL);
}
else if ( child < 0 ) {
cout << "\nSomething wen't wrong in the forking process\n";
}
else {
}
child = fork();
if ( child > 0 ) {
cout << "\nSecond child is in charge\n";
execlp("locate", "locate", "etc", NULL);
}
else if ( child < 0 ) {
cout << "\nSomething went wrong in the forking of second child!\n";
}
else {
}
现在这会显示Child #1 is in charge
和Second child is in charge
然后它会混合两个命令(我在ls
}之间看到一些etc
。
我尝试过第二件事:
using namespace std;
int main() {
int status;
pid_t child;
pid_t ch_status = waitpid(child, &status, WNOHANG);
child = fork();
if ( child > 0 ) {
cout << "\nChild is in charge\n";
execlp("ls", "ls", NULL);
}
else if ( child < 0 ) {
cout << "\nSomething wen't wrong in the forking process\n";
}
if ( ch_status == 0 ) {
}
else if ( ch_status == -1 ) {
cout << "\nERROR IN CHILD #1\n";
}
else {
}
child = fork();
if ( child == 0 ) {
cout << "\nSecond child is in charge\n";
execlp("locate", "locate", "etc", NULL);
}
else if ( child < 0 ) {
cout << "\nSomething went wrong in the forking of second child!\n";
}
if ( ch_status == 0 ) {
}
else if ( ch_status == -1 ) {
cout << "\nERROR IN CHILD #1\n";
}
else {
}
child = fork();
if ( child > 0 ) {
cout << "\nThird child is in charge!\n";
execlp("echo", "echo", "herro", NULL);
}
else if ( child < 0 ) {
cout << "\nForking of third child failed!\n";
}
if ( ch_status == 0 ) {
}
else if ( ch_status == -1 ) {
cout << "\nERROR IN CHILD #2\n";
}
else {
}
return 0;
}
这更基于我提供的链接,它产生了与我做的第一次测试运行相同的结果,除了它还会显示ERROR IN CHILD #1/2
。
这些命令无关紧要,我只是不明白我在这里做错了什么......我也尝试将它们嵌套在else { //start second fork here }
中,但我也无处可去。
根据我的理解,阅读waitpid(2)
手册,我应该使用WNOHANG
;
http://linux.die.net/man/2/waitpid
非常感谢任何建议/指示。
如果可能,请提交一份示例代码,说明如何完成正确的结果(execute command 1 -> wait until done -> execute command 2 -> exit)
。
期待回复。
答案 0 :(得分:2)
你应该在之后调用父中的waitpid()
。也就是说,它应该进入child > 0
分支。
该功能的目的是等待子状态的改变。&#34;但是,在你产生孩子之前,你要调用它。
代码应如下所示:
using namespace std;
int main() {
int status;
pid_t child;
child = fork();
if ( child == 0 ) {
cout << "\nChild is in charge" << endl;
execlp("ls", "ls", NULL);
} else if ( child < 0 ) {
cout << "\nSomething wen't wrong in the forking process" << endl;
} else {
cout << "Parent waiting" << endl;
pid_t ch_status = waitpid(child, &status, WNOHANG);
if (ch_status == -1) {
cout << "\nERROR IN CHILD #1" << endl;
}
}
child = fork();
//same procedure as above
}
答案 1 :(得分:1)
根据输出刷新的顺序,您错误地判断输出语句执行的顺序。虽然在执行相应的语句之前无法刷新输出,但您的代码中没有刷新调用。因此,以后很多会发生冲洗。
使用endl
而不是在行尾添加\n
。 endl
操纵器包括刷新。