Possible Duplicate:
In Linux, how to prevent a background process from being stopped after closing SSH client
I have a C program which I access and interact with over terminal (usually from SSH on a linux box). I have been trying to find the solution to the problem where after I close the terminal/logout, the process ends with it (the program basically asks for some options then goes about its business with no further interaction required so I would like to have it continue to run even after I logout of SSH).
There are ways in linux to avoid this such as 'screen', but I want to do it programatically with C without relying on installed packages such as screen- even if this means reinventing the wheel.
So far I understand fork()
to be the standard trivial way to daemonize a process, so could anyone help me to finish the code that allows the above described process to happen?
Within parent:
main()
{
//Do interactive stuff
signal(SIGCHLD, SIG_IGN); //stops the parent waiting for the child process to end
if(fork())
exit(0);
// and now the program continues in the child process
I can now logout of SSH which closes the original shell...and the child continues its work!
Within child:
//Continue with processing data/whatever the program does (no input/output to terminal required)
exit(0);
to detach the process from the parent:
use setsid() on the children process, it will run the program in new session
sid = setsid();
To Keep a program running even when the terminal is closed:
SIGHUP is a signal sent to a process when its controlling terminal is closed.
try to ignore it using
signal (SIGHUP, SIG_IGN);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With