如何使用fork()来守护进程子进程独立的它的父? [英] How to use fork() to daemonize a child process independant of it's parent?

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

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/285015/linux-$p$pvent-a-background-process-from-being-stopped-after-closing-ssh-client\">Linux: prevent从关闭SSH客户端

后被停止的后台进程

我有我(在Linux中通常SSH)在终端接入,并与之交互的C程序。我一直想在那里后,我关闭终端/注销,这个过程用它结束(程序基本要求的一些选项,然后处理其业务,无需进一步互动,所以我想拥有它,找到解决问题的办法继续即使我退出SSH运行)。

有在Linux的方式来避免这种情况,如屏幕,但我想用C做编程不依赖于安装的软件包,如筛查即使这意味着重新发明轮子。

到目前为止,我明白fork()的是,以守护进程的过程标准琐碎的方式,所以任何人都可以帮助我完成code,使上述过程发生?

在父:

 的main()
{//做互动的东西信号(SIGCHLD,SIG_IGN); //停止父等待子进程结束如果(叉())
 出口(0);
//现在的程序继续在子进程

我现在可以注销其SSH关闭原壳......而孩子继续工作!的

在小孩:

  //与数据处理/不管程序是否​​继续(无输入/输出端所需)
出口(0);


解决方案

从父分离过程

对孩子过程使用setsid(),将在新的会话中运行该程序

  SID = setsid();

一起来看看在<一个例子href=\"http://www.itp.uzh.ch/~dpotter/howto/daemonize\">http://www.itp.uzh.ch/~dpotter/howto/daemonize


为了保持一个程序即使在终端关闭运行

SIGHUP时发送到其控制终端闭合的过程的信号。

尝试使用忽略它。

 信号(SIGHUP,SIG_IGN);

Possible Duplicate:
Linux: 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();

take a look at the example on http://www.itp.uzh.ch/~dpotter/howto/daemonize


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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆