【问题标题】:Why my atexit function not working in linux为什么我的 atexit 函数在 linux 中不起作用
【发布时间】:2022-11-13 21:00:53
【问题描述】:

我使用 fork() 创建进程并将 exit(0) 放在最后,然后将 atexit(func) 放在最后,这样我可以在进程退出或不退出时收到通知以避免僵尸进程。 但是,atexit 没有输出,所以我想也许我已经制作了僵尸进程。谁能告诉我为什么我的 atexit 输出没有显示?

//fork parent process (first process fork):
    if ((pid = fork()) == 0) {
        printf("parent1: %d in %d\n", getpid(), getpgid(pid));
        atexit(endfunc);
        char* argf[MAXARGS];
        int a;
        printf("buf: %s\n", buf);
        if (strchr(cmdline, '|') != NULL) {
            a = make_tokens(buf, 0, argf, "|");
            printf("In pipe\n");
            int fd[200][2];
            pid_t pids[200];
            for (int i = 0; i < a - 1; i++) {
                pipe(fd[i]);

//somewhere in parent fork child:
         if ((pids[0] = fork()) == 0) {
             printf("child: %d in %d\n", getpid(), getpgid(pid));
             atexit(endfunc);
             close(fd[0][0]);
             for (int i = 1; i < a - 1; i++) {
                  close(fd[i][0]);
                  close(fd[i][1]);
             }
             char* arg[MAXARGS];
             parseline(argf[0], arg);
             execvp(arg[0], arg);
             exit(0);
         }

//at the end of parent process wait for childrens
        pid_t wpid;
        for (int i = 0; i < a; i++) {
            wpid = waitpid(pids[i], NULL, 0);
            if (wpid < 0) {
                perror("waitpids");
            }
            else if (wpid >= 0) {
                printf("wait for %d\n", pids[i]);
            }
        exit(0);//parent process exit

//endfunc: function for atexit()
    void endfunc(void) {
         printf("process %d ended\n", getpid());
    }

这是我输入 ls -al | 后的输出grep t:

mini> ls -al | grep t
parent1: 23154 in 23140
buf: ls -al | grep t
In pipe
child: 23155 in 23140
child: 23156 in 23140

//output for command

wait for 23155
wait for 23156
process 23154 ended
wait for 23154

正如我们所见,父进程已经结束并打印了 atexit。但是,子进程已经创建,但是子进程的 atexit 还没有出来。我的子进程还没有退出吗?

【问题讨论】:

标签: c linux


【解决方案1】:

From the atexit manual page:

成功调用 exec(3) 函数之一后,所有注册都将被删除。

因为成功的exec 调用将代替进程代码,包括您在atexit 注册的那个,您的退出代码不能再被调用,因此是“未注册的”。

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 2021-03-21
    • 2021-12-18
    • 2011-06-23
    • 1970-01-01
    • 2017-08-18
    • 2010-10-18
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多