编写一个Linux守护进程时,为什么必须从tty的分离? [英] Why MUST detach from tty when writing a linux daemon?

查看:522
本文介绍了编写一个Linux守护进程时,为什么必须从tty的分离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试着写用C linux下的一个守护进程,有人告诉我,我要补充以下后,code code座:

When i tried to write a daemon under linux using C, i was told i should add following code after fork code block:

/* Preparations */
...

/* Fork a new process */
pid_t cpid = fork();
if (cpid == -1){perror("fork");exit(1);}
if (cpid > 0){exit(0);}

/* WHY detach from tty ? */
int fd = open("/dev/tty", O_RDWR);
ioctl(fd, TIOCNOTTY, NULL);

/* Why set PGID as current PID ? */
setpgid(getpid(), 0);

我的问题是:
有一个必须做以上操作?

My question is: Is there a must to do the above operations?

推荐答案

您必须从终端撇清您的守护进程,以避免被涉及到终端的操作(如SIGHUP发送信号时,终端会话结束以及可能SIGTTIN和SIGTTOU )。

You must disassociate your daemon process from the terminal to avoid being sent signals related to terminal's operation (like SIGHUP when the terminal session ends as well as potentially SIGTTIN and SIGTTOU).

不过请注意,从使用TIOCNOTTY 的ioctl 终端解除关联的方式在很大程度上已经过时。您应该使用 setsid() 来代替。

Note however that the way of disassociating from the terminal using TIOCNOTTY ioctl is largely obsolete. You should use setsid() instead.

原因守护进程离开其原来的进程组是不接收发送到该组的信号。需要注意的是 setsid()还使你的程序在自己的进程组。

The reason for a daemon to leave its original process group is not to receive signals sent to that group. Note that setsid() also places your process in its own process group.

这篇关于编写一个Linux守护进程时,为什么必须从tty的分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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