Fork, execlp and kill. Zombie process

ぃ、小莉子 提交于 2021-02-20 04:13:06

问题


I have a c program that executes another process (bash script) with fork and execlp. When I want to kill this process it moves to a zombiee state. Why is this??

Create a process:

    switch (PID_BackUp= fork())
    {
      case -1:
          perror("fork");
          printf("An error has occurred launching backup.sh script!\n");
          break;

      case 0:
          execlp("/usr/local/bin/backup.sh", "/usr/local/bin/backup.sh", NULL, NULL, NULL);
          break;

      default:
          printf("backup.sh script launched correctly! PID: %d\n", PID_BackUp);
          break;
    }

Kill a process:

    if(kill(PID_BackUp,SIGKILL)==-1)
        fprintf(stderr, "No se ha podido matar el programa: %d\n", PID_BackUp);
    else
        printf("\nProceso con identificador %d, se ha abortado\n", PID_BackUp);

So at this point the process moves to a zombie state. What I am doing wrong?


回答1:


You should call waitpid(2) or some other waiting system call (wait4(2)...) to avoid having zombie processes. BTW you may also handle the SIGCHLD signal to be notified when a child process has terminated (or changed state).

Generally, you'll better first kill(2) a process with SIGTERM (and only later, with SIGKILL) since that process -your backup.sh script- could handle correctly (using trap builtin in the shell script) the signal (but SIGKILL cannot be caught, and the backup could e.g. leave clutter or useless files on the disk). See also signal(7) & signal-safety(7)

Read Advanced Linux Programming (we can't explain what is taught by that freely available book in several chapters in only a few paragraphs).

BTW, better use perror(3) or strerror(errno) in messages when a system call fails.



来源:https://stackoverflow.com/questions/44195251/fork-execlp-and-kill-zombie-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!