Home > Blockchain >  Why my atexit function not working in linux
Why my atexit function not working in linux

Time:11-13

I made processes with fork() and put exit(0) at the end and atexit(func) so I can get notice when process is exited or not to avoid zombie processes. However, there are no output for atexit so I think maybe I have made zombie process. Can anyone tell me why my atexit output doesn't show?

//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());
    }

This is the output after I input 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

As we can see, parent process has ended well and atexit printed. However, child processes has been made but atexit for child has not cameout.Has my child processes has not been exited?

CodePudding user response:

From the atexit manual page:

Upon a successful call to one of the exec(3) functions, all registrations are removed.

Because a successful exec call will replace the process code, including the one you registered with atexit, your exit code can no longer be called and is thus "unregistered".

  • Related