Home » Questions » Computers [ Ask a new question ]

Automatically restart a Unix job if it goes down?

Automatically restart a Unix job if it goes down?

I have a job that I would like to "daemonize" on Unix: I want it to come up when the computer boots, and I want it to restart if it goes down.

Asked by: Guest | Views: 257
Total answers/comments: 4
Guest [Entry]

"This approach is fast and cheap and not bulletproof:

#!/usr/bin/perl -w
$l = `ps x`;
if (not $l =~ /mzscheme/) {
system('~/utils/src/plt/bin/mzscheme &');
}

I put that script in a cron file."
Guest [Entry]

"This approach is fast and cheap and not bulletproof:

#!/usr/bin/perl -w
$l = `ps x`;
if (not $l =~ /mzscheme/) {
system('~/utils/src/plt/bin/mzscheme &');
}

I put that script in a cron file."
Guest [Entry]

"Another idea (similar to Jeffrey Aylesworth's file lock suggestion, though more geared to the Unix shell-scripting world) would be to have your cron job check a PID-file (see related questions on SO). If your daemonized application doesn't create a PID file on its own, you can wrap it in a shell script to do so.

The basic idea is this:

Start your application from a script that creates a PID-file (somewhere like /home/username/run/Foo.pid) containing its PID.
In your cron job, check that the PID-file exists.

If it exists, check that the PID is still running the application.
If not running or the PID-file doesn't exist, application has died. Restart.

If you only ever want to have the application Foo running once, you could even do all this in the startup script, and just execute that as the cron job."
Guest [Entry]

"You can use systemd. Most modern systems already use it.

Use Type=Simple

Type=simple (default): systemd considers the service to be started up immediately. The process must not fork. Do not use this type if other services need to be ordered on this service, unless it is socket activated.

Source: wiki.archlinuxdotorg/index.php/systemd#Service_types

And Restart=always

Please don't do the forking-magic yourself, since other tools already do this (and better than you and I can do it)."