1

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.

4

1 回答 1

2

我想问题就在这里

ptrace(PTRACE_TRACEME, 0, NULL, NULL);

和这里

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

如果进程状态发生变化,wait4(顺便说一下不推荐使用)返回控制权。

ptrace(PTRACE_TRACEME force child send to parent SIGTRAP if some condition occur, and every time wait4, waitpid and similar functions return control to you, you need to use WIFEXITED 区分子进程退出和 SIGTRAP 条件。

您可以通过将 wait4 调用替换为以下内容来检查我的声明:

    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");
于 2013-07-17T00:49:01.893 回答