I know os.setsid() is to change the process(forked) group id to itself, but why we need it?
I can see some answer from Google is: To keep the child process running while the parent process exit.
But according to my test below, without os.setsid() the child process won't exit as well even if the parent process exit(or being killed). So why we need to add os.setsid()? Thanks.
import os
import time
import sys
mainPid = os.getpid()
print("Main Pid: %s" % mainPid)
pid = os.fork()
if pid > 0:
time.sleep(3)
print("Main process quit")
sys.exit(0)
#os.setsid()
for x in range(1, 10):
print("spid: %s, ppid: %s pgid: %s" % (os.getpid(), os.getppid(), os.getpgid(0)))
time.sleep(1)
Calling
setsidis usually one of the steps a process goes through when becoming a so called daemon process. (We are talking about Linux/Unix OS).With
setsidthe association with the controlling terminal breaks. This means that the process will be NOT affected by a logout.There are other way how to survive a logout, but the purpose of this 'daemonizing' process is to create a background process as independent from the outside world as possible.
That's why all inherited descriptors are closed; cwd is set to an appropriate directory, often the root directory; and the process leaves the session it was started from.
A double
forkapproach is generally recommended. At eachforkthe parent exits and the child continues. Actually nothing changes except the PID, but that's exactly what is needed here.First
forkbefore thesetsidmakes sure the process is not a process group leader. That is required for a succesfullsetsid.The second
forkafter thesetsidmakes sure that a new association with a controlling terminal won't be started merely by opening a terminal device.NOTE: when a daemon process is started from
systemd, thesystemdcan arrange everything described above so the process does not have to.