When the original address parent process exits unexpectedly, ensure that the child process exits the preface
When the parent process exits unexpectedly, if the child process does not exit, or if the parent process's exit is not known, it will cause the child process to become an orphan process, and worse, if the parent process needs to use a port, and the parent process exits unexpectedly, and the parent process starts again, it discovers that its child process occupies its port. The reason is that the child process inherits the port of the original parent process.
It is therefore important to ensure that the parent process exits unexpectedly and that the subprocess can exit.
The system function is overwritten, as in the following procedure.
bakrun.sh
#!/bin/bash
declare-i i=1
until ((30<i)) do-let i++-sleep
1
echo ' 1 ' done
exit 0
BAKRUN.C, compiling: gcc-g bakrun.c-o bakrun
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h >
#include <unistd.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/wait.h>
int Mysystem (const char *cmd)
{
pid_t pid;
int status;
if ((Pid=fork ()) < 0)
{
printf ("fork error\n");
}
else if (PID >0)
{
waitpid (pid,&status,0);
printf ("parent\n");
}
else
{
printf ("Receive msg\n");
Prctl (pr_set_pdeathsig,sighup);
Execl ("/bin/sh", "sh", "-C", "./bakrun.sh", (char*) 0);
printf ("exec cmd\n");
return-1;
}
return 0;
}
int main (int argc, char* argv[])
{
Mysystem ("./backrun.sh");
while (1);
return 0;
}
In the above program, you need to set the options
Prctl (Pr_set_pdeathsig,sighup);
Set this option, after the parent process is dead, the child process receives the SIGHUP signal, and the subprocess exits, resolves, the parent process exits unexpectedly, and the child process is too late to reclaim the resource.
If you remove the above setting, after killing Bakrun, you will find that the SH script is still running.
Original link:
Http://www.huyanbing.me/2017/09/10/%E7%88%B6%E8%BF%9B%E7%A8%8B%E5%BC%82%E5%B8%B8%E9%80%80%E5%87%BA%E6%97%B6%EF %bc%8c%e5%ad%90%e8%bf%9b%e7%a8%8b%e4%b9%9f%e9%80%80%e5%87%ba/