我有一个命令和一些输入,当在命令行上运行时会返回一个错误,相关的错误代码为 1:
$ foo bar
[some useful error message...]
$ echo $?
1
我正在尝试使用以下方法捕获此错误代码waitpid()
:
...
char *proc_cmd = "foo bar"
pid_t proc = popen4(proc_cmd, in_fd, out_fd, err_fd, POPEN4_FLAG_NONE);
...
if (waitpid(proc, &global_foo_status, WNOHANG | WUNTRACED) == -1) {
/* process failed */
}
...
pthread_create(&proc_thread, NULL, perform_foo_function, bar_data);
pthread_join(proc_thread, (void **) NULL);
...
我的线程将一直运行perform_foo_function()
,直到不再bar_data
需要处理,或者直到进程由于数据错误而失败:
static void * perform_foo_function (data *bar_data) {
/* check before */
if (WIFEXITED(global_foo_status)) {
int exit_status = WEXITSTATUS(global_foo_status);
if (exit_status != 0)
/* process failed */
}
/* do stuff with bar_data */
while (bar_data) {
/* causes error ... */
}
/* check after */
if (WIFEXITED(global_foo_status)) {
int exit_status = WEXITSTATUS(global_foo_status);
if (exit_status != 0)
/* process failed */
}
pthread_exit(NULL);
}
我的问题是如何捕捉这个过程的错误状态?在调试过程中WEXITSTATUS
,无论我是故意制造错误情况还是提供合法输入,都始终为零。
我对相关的状态代码检查有什么误解waitpid()
,我应该进行哪些更改才能使其正常工作?
跟进
以下代码似乎工作,没有阻塞:
...
char *proc_cmd = "foo bar"
pid_t global_foo_pid = popen4(proc_cmd, in_fd, out_fd, err_fd, POPEN4_FLAG_NONE);
...
if (waitpid(global_foo_pid, &global_foo_status, WNOHANG | WUNTRACED) == -1) {
/* process failed */
}
...
pthread_create(&proc_thread, NULL, perform_foo_function, bar_data);
pthread_join(proc_thread, (void **) NULL);
...
static void * perform_foo_function (data *bar_data)
{
/* do stuff with bar_data */
while (bar_data) {
/* causes error ... */
}
/* check after */
if (WIFEXITED(global_foo_status)) {
waitpid(global_foo_pid, &global_foo_status, WUNTRACED);
int exit_status = WEXITSTATUS(global_foo_status);
if (exit_status != 0)
/* process failed */
}
pthread_exit(NULL);
}
我猜“检查后”waitpid()
调用不会挂起,因为该过程已经在此步骤退出。