我有一个C程序,我可以通过终端访问和交互(通常来自Linux机器上的SSH).我一直试图找到问题的解决方案,在我关闭终端/注销后,流程以它结束(程序基本上要求一些选项然后进行业务,不需要进一步的交互,所以我想拥有它在我注销SSH之后继续运行).
在Linux中有一些方法可以避免这种情况,例如"屏幕",但我想用C编程,而不依赖于屏幕等已安装的软件包 - 即使这意味着重新发明轮子.
到目前为止,我理解fork()成为守护进程的标准琐碎方法,所以任何人都可以帮助我完成允许上述过程发生的代码吗?
在父母内部:
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
Run Code Online (Sandbox Code Playgroud)
我现在可以注销关闭原始shell的SSH了......孩子继续工作!
在孩子内:
//Continue with processing data/whatever the program does (no input/output to terminal required)
exit(0);
Run Code Online (Sandbox Code Playgroud)
Ami*_*sef 12
将进程与父进程分离:
在子进程上使用setsid(),它将在新会话中运行程序
sid = setsid();
Run Code Online (Sandbox Code Playgroud)
即使终端关闭,也要保持程序运行:
SIGHUP是在其控制终端关闭时发送给进程的信号.
试着用它来忽略它
signal (SIGHUP, SIG_IGN);
Run Code Online (Sandbox Code Playgroud)