How to terminate a child process which is running another program by doing exec

前端 未结 3 859
予麋鹿
予麋鹿 2021-02-06 15:56

I\'m doing fork in my main program,and doing exec in the child process which will run another program. Now i want to terminate the child(i.e., the program invoked by exec) and r

相关标签:
3条回答
  • 2021-02-06 15:58

    Either in or outside your program, it is possible to use kill. By including <signal.h>, you can kill a process with a given PID (use the fork return value to do this).

    #include <signal.h>
    
    int pid;
    
    switch (pid = fork())
    {
    case -1:
      /* some stuff */
      break;
    case 0: 
      /* some stuff */
      break;
    default:
      /* some stuff */
      kill(pid, SIGTERM);
    }
    

    It is also possible to use kill command in the shell. To find the PID of your child process, you can run ps command.

    man kill
    The kill() function shall send a signal to a process or a group of processes specified by pid. The signal to be sent is specified by sig and is either one from the list given in <signal.h> or 0. If sig is 0 (the null signal), error checking is performed but no signal is actually sent. The null signal can be used to check the validity of pid.

    0 讨论(0)
  • 2021-02-06 16:10

    POSIX defines the kill(2) system call for this:

    kill(pid, SIGKILL);
    
    0 讨论(0)
  • 2021-02-06 16:12

    You need to do the following:

    1. Do a kill(pid, SIGTERM) first - this gives the child process an opportunity to terminate gracefully
    2. Wait a period of time (use sleep). The period of time depends on the time the child process takes to close down gracefully.
    3. Use waitpid(pid, &status, WNOHANG) checking the return value. If the process has not aborted do step 4
    4. Do a kill(pid, SIGKILL) then harvest the zombie by doing waitpid(pid, &status, 0).

    These steps ensure that you give the child process to have a signal handler to close down and also ensures that you have no zombie processes.

    0 讨论(0)
提交回复
热议问题