为什么fork()的setsid()之前 [英] Why fork() before setsid()

查看:381
本文介绍了为什么fork()的setsid()之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么叉() setsid()来守护进程的程序?

Why fork() before setsid() to daemonize a process?

基本上,如果我想从它的控制终端分离的过程,并使其成为一个进程组组长:我用 setsid()

Basically, if I want to detach a process from its controlling terminal and make it a process group leader : I use setsid().

这样做没有分叉之前不起作用。

Doing this without forking before doesn't work.

为什么?

推荐答案

首先:setsid()将让您的加工工艺组组长,但它也将让你一个新的会话的领导者。如果你是在让自己的过程组有兴趣,然后使用setpgid(0,0)。

First of all: setsid() will make your process a process group leader, but it will also make you the leader of a new session. If you are just interested in getting your own process group, then use setpgid(0,0).

现在了解的实际原因setsid()返回EPERM如果你已经是工艺组组长或会话的领导者,你必须明白,进程组和会话ID从进程的进程ID创建它们(从而导致初始化其中,即对于会话组长的pid == SID和一个进程组长的pid == PGID)。此外流程组不能在会话之间移动。

Now for understanding the actual reason why setsid() returns EPERM if you already are process group leader or session leader you have to understand that process group and session ids are initialized from the process id of the process creating them (and hence leading them, i.e. for a session leader pid == sid and for a process group leader pid == pgid). Also process groups cannot move between sessions.

这意味着,如果你是一个进程组长,并创建一个新的会话将被允许再SID和PGID会得到设为您的PID,留在你的老工艺组中的其他过程以一种不可思议的状态:他们的过程组长突然在不同的会话,然后他们自己可能。并且不能被允许的,因此EPERM由内核

That means if you are a process group leader, and creating a new session would be allowed then the sid and the pgid would get set to your pid, leaving the other processes in your old process group in a weird state: their process group leader suddenly is in a different session then they themselves might be. And that cannot be allowed, hence the EPERM by the kernel.

现在,如果你fork()的,一旦你既不是会议也不过程组长了,因此你的SID和PGID设置为您pid是安全的,因为有这样的组中没有其他进程。

Now if you fork() once you are neither session nor process group leader anymore and hence setting your sid and pgid to your pid is safe, because there are no other processes in such group.

所以,YEPP,仔细想想,这一切是有道理的。

So, yepp, think about it, it all makes sense.

这篇关于为什么fork()的setsid()之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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