守护独立于其父进程的子进程

守护独立于其父进程的子进程

本文介绍了如何使用fork()守护独立于其父进程的子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C 程序,可以通过终端访问该程序并与之交互(通常是从Linux机器上的SSH).我一直在尝试寻找问题的解决方案,在关闭终端/注销之后,该过程以该过程结束(该程序基本上要求一些选项,然后进行其业务,而无需进一步的交互,所以我希望拥有它即使我注销SSH后仍继续运行).

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).

Linux中有很多方法可以避免这种情况,例如屏幕",但是我想以编程方式使用 C 来做到这一点,而不依赖于诸如screen之类的已安装软件包,即使这意味着需要重新发明轮子.

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.

到目前为止,我了解fork()是守护进程的标准琐碎方法,所以有人可以帮助我完成允许上述过程发生的代码吗?

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?

在父级中:

 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

我现在可以注销SSH,从而关闭原始外壳...孩子继续工作!

I can now logout of SSH which closes the original shell...and the child continues its work!

在孩子中:

//Continue with processing data/whatever the program does (no input/output to terminal required)
exit(0);

推荐答案

将流程与父级分离:

在子进程上使用setsid(),它将在新会话中运行程序

use setsid() on the children process, it will run the program in new session

 sid = setsid();


即使终端关闭也要保持程序运行:

SIGHUP是在其控制终端关闭时发送到进程的信号.

SIGHUP is a signal sent to a process when its controlling terminal is closed.

尝试使用

signal (SIGHUP, SIG_IGN);

这篇关于如何使用fork()守护独立于其父进程的子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:43