为什么在编写 linux 守护进程时必须与 tty 分离? [英] Why MUST detach from tty when writing a linux daemon?

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

问题描述

当我尝试使用 C 在 linux 下编写守护程序时,有人告诉我应该在 fork 代码块之后添加以下代码:

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天全站免登陆