0

コマンドラインで実行するとエラーが返されるコマンドといくつかの入力があり、関連するエラーコードは 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()呼び出しはハングしないと思います。

4

1 に答える 1