wait4 do not block parent thread

2019-08-13 11:46发布

I have two following source files

loop.c which executable name is loop

int main() {
    while(true);
    return 0;
}

and run.c which executable name is run

int main() {
    pid_t child_pid = fork();

    int status;
    struct rusage info;

    if (child_pid == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execl("loop", "loop", NULL);
        exit(0);
    }

    wait4(child_pid, &status, 0, &info);

    puts("Child exited");
    printf("%ld\n", info.ru_utime.tv_usec);

    return 0;
}

I've compiled both and I've ran run program. Why it terminated? I've read that wait4 suspend, but in fact it does not. When I've executed ps program loop is running and run does not (it's not in ps and terminal seems to finish it's work by giving an output).

Am I missing something?

PS

I used gnu g++ compiler if it's matters.

1条回答
Animai°情兽
2楼-- · 2019-08-13 12:06

I suppose the problem is here

ptrace(PTRACE_TRACEME, 0, NULL, NULL);

and here

wait4(child_pid, &status, 0, &info);

wait4 (deprecated by the way) return control if process state changed.

ptrace(PTRACE_TRACEME force child send to parent SIGTRAP if some condition happen, and every time wait4, waitpid and similar functions return control to you, you need use WIFEXITED to distinguish between exit of child process and sigtrap condition.

You can check my statement by replacing wait4 call with:

    if (wait4(child_pid, &status, 0, &info) < 0) {
        perror("wait4 failed");
    } else if (WIFEXITED(status)) {
        printf("process exit\n");
    } else
        printf("child just send signal\n");
查看更多
登录 后发表回答