Thursday, August 20, 2009

Tip of the day : Linux - How to keep commands running in the background after logging out

Yes I know this is the 2nd tip of the day but this one is simple. Today a colleague of mine come to me with this scenario :
I'm starting a ping on console. Then I'm exiting console, and would like to return my ping session. How can I do this ?
Normally in order to send a command to background and redirect STDOUT & STDERR to a logfile we use :
ping localhost >> /var/log/neco.test 2>&1 &
[2] 27783
Even if you send a process to the background when you logout/exit from a shell session Linux shell sends a HUP signal and kills that process. So we need to detach this process from shell. At this point the command nohup helps us. nohup detach the process from shell and attach to initd which is the mother process of all :) So we modify our command as below to reach our target :
nohup ping localhost >> /var/log/neco.test 2>&1 &
[1] 27786
After this command we can exit the shell and check the status of the STDOUT from the log file :
tail -f /var/log/neco.test
64 bytes from necoPC (127.0.0.1): icmp_seq=105 ttl=64 time=0.023 ms
64 bytes from necoPC (127.0.0.1): icmp_seq=106 ttl=64 time=0.022 ms
64 bytes from necoPC (127.0.0.1): icmp_seq=107 ttl=64 time=0.019 ms
In order to kill the process we need to use kill command with process id.

No comments:

Post a Comment