我有一個命令和一些輸入,當在命令行中運行會返回一個錯誤,與1相關的錯誤代碼:沒有抽到waitpid函數()返回正確WEXITSTATUS錯誤條件
$ 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()
電話不掛,因爲該工藝具有已經退出這一步。