Saturday, July 27, 2013

Keep command launching after logout from terminal

It is very common case - you need to login to linux box, launch smth huge and that takes time, but you do not want to wait its finish and want to logout, or you afraid that internet connection could be broken in the middle of process that terminate your process.

thanks a lot for explanation to Dennis Williamson at here.

Two scenarios:
1) You launch process in background:

$ nohup myprogram &
$ logout

Explanation: nohup is allow process to ignore termination signal SIGHUP (“hang-up”)  on your logout (manual), "&" - just launch process in background and do not block current terminal session.

2) You launched process but forget to do it in background:

$ myprogram
<press Ctrl+Z>
[1]+  Stopped     myprogram
$ disown -h %1
$ bg 1
[1]+ myprogram &
$ logout

Explanation (copy-paste from stackoverflow):
You press ctrl-Z. The system suspends the running program, displays a job number and a "Stopped" message and returns you to a bash prompt. You type the "disown -h %1" command (here, I've used a "1", but you'd use the job number that was displayed in the "Stopped" message) which marks the job so it ignores the SIGHUP signal (it will not be stopped by logging out). Next, type the "bg" command using the same job number. This resumes the running of the program in the background and a message is displayed confirming that. You can now log out and it will continue running...
 ...You should be aware that when you use the "bg" command the result is the same as if you'd run your program in the background with an ampersand (&). It won't have any output to stdout so it should be made to write output to a file (nohup will redirect standard output to nohup.out or ~/nohup.out if you don't redirect it yourself).

FYI: to resume to stopped process to foreground you can use "fg" of "fg <number>" in our case "fg 1", where "<number>" - is number that shown after Ctrl+z.

No comments:

Post a Comment