Self-restart program on segfault for Linux

On Linux, what would be the best way to restart a program on crash by catching an exception in crashhandler (e.g. segfault)?

+3
source share
7 answers

You may have a loop in which you essentially fork()do the real work in the child and just wait for the child and check its exit status in the parent. You can also use a system that monitors and restarts programs in a similar way, for example, daemontools, runit, etc.

+6
source

the simplest

while [ 1 ]; do ./program && break; done

, , 0, .

+9

SIGSEGV (. man 3 signal man 2 sigaction), exec . (SIGFPE, SIGILL, SIGBUS, SIGSYS,...).

, . unix, ( ).

SIGTERM, - , , SIGKILL, .

+7

, :

- , getty daemon. . /Etc/inittab inittab (5). , , -).

. , .

# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6
+3

, , crontab(1), script, , .

0

, , , :)

Most enterprise solutions are actually just bizarre ways of grepping output from ps()for a given line and performing an action if certain criteria are met - that is, if your process is not found, then call start script.

0
source

Try using the following code if it is defined for segfault. This can be changed as needed.

#include <stdio.h> 
#include <signal.h> 
#include <setjmp.h> 
#include <poll.h>

sigjmp_buf buf; 
void handler(int sig) { 
siglongjmp(buf, 1); 
} 
int main() { 
//signal(SIGINT, handler); 
//register all signals
struct sigaction new_action, old_action;
new_action.sa_handler = handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;

sigaction (SIGSEGV, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGSEGV, &new_action, NULL);

if (!sigsetjmp(buf, 1)){
printf("starting\n"); 
//code or function/method here
}
else{  
printf("restarting\n"); 
 //code or function/method here
}
while(1) {
poll(NULL,0,100); //ideally use usleep or nanosleep. for now using poll() as a timer
printf("processing...\n");
}
return 0; //or exit(SUCESS)
}
0
source

Source: https://habr.com/ru/post/1764562/


All Articles