简体   繁体   English

C++ 多次等待进程完成?

[英]C++ waiting for process to finish multiple times?

Help me correct my confusion, I have a job running in bg with pid = 3帮我纠正我的困惑,我有一份工作在 pid = 3 的 bg 中运行

I want to check if it has finished every 10 sec (non blocking) and print hello once and stop;我想检查它是否每 10 秒完成一次(非阻塞)并打印一次 hello 并停止;

But someone claimed the following:但是有人声称以下内容:

  1. this won't work as status can be consumed only once .这不起作用,因为状态只能消耗一次

  2. Even if you stopped after first run, your check isn't right.即使您在第一次运行后停止,您的检查也不正确。 you should check returned pid_t value and status too.您也应该检查返回的 pid_t 值和状态。

and he added:他补充说:

just remember that waitpid is waiting for state change, and if a previous call has already consumed this change, the second call will block for other changes请记住,waitpid 正在等待 state 更改,如果之前的调用已经消耗了此更改,则第二次调用将阻塞其他更改

I am just confused with this status a lot, can someone help me understand.我只是对这种状态感到困惑,有人可以帮助我理解。 I don't find any good and clear reference online.我在网上找不到任何好的和明确的参考。

I think your code should work.我认为您的代码应该可以工作。

  1. You're not using the status argument, so that doesn't matter.您没有使用status参数,所以没关系。
  2. You only have to check status if you need to distinguish different ways of the process ending, such as by a signal versus normal exit.如果您需要区分进程结束的不同方式,例如通过信号与正常退出,您只需检查status For instance you can use WIFSIGNALED(status) to tell if it exited due to a signal, and you can use WEXITSTATUS(status) to get the value that it passed to exit() .例如,您可以使用WIFSIGNALED(status)来判断它是否由于信号而退出,并且可以使用WEXITSTATUS(status)来获取它传递给exit()的值。

The last comment only matters if you have some other wait() or waitpid() call that might detect the process exiting.只有当您有其他可能检测到进程退出的wait()waitpid()调用时,最后一条评论才重要。 If this is the only one, you should be fine.如果这是唯一的,你应该没问题。

If the code is in a loop, put break after you print Hello to stop checking.如果代码处于循环中,请在打印Hello后放置break以停止检查。

It would be good to check if return_pid == -1 , which indicates an error, and stop the loop.检查是否return_pid == -1表示错误并停止循环会很好。 If somehow the status was received by some other wait call, you'll get an error and this will keep you from retrying forever.如果其他等待调用以某种方式收到了状态,您将收到一个错误,这将使您永远无法重试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM