Why use os.setsid() in Python?

2024/9/25 6:23:18

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 sysmainPid = 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)
Answer

Calling setsid is usually one of the steps a process goes through when becoming a so called daemon process. (We are talking about Linux/Unix OS).

With setsid the 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 fork approach is generally recommended. At each fork the parent exits and the child continues. Actually nothing changes except the PID, but that's exactly what is needed here.

First fork before the setsid makes sure the process is not a process group leader. That is required for a succesfull setsid.

The second fork after the setsid makes 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, the systemd can arrange everything described above so the process does not have to.

https://en.xdnf.cn/q/71609.html

Related Q&A

How to apply different aggregation functions to same column by using pandas Groupby

It is clear when doingdata.groupby([A,B]).mean()We get something multiindex by level A and B and one column with the mean of each grouphow could I have the count(), std() simultaneously ?so result loo…

Can not connect to an abstract unix socket in python

I have a server written in c++ which creates and binds to an abstract unix socket with a namespace address of "\0hidden". I also have a client which is written in c++ also and this client can…

Pandas display extra unnamed columns for an excel file

Im working on a project using pandas library, in which I need to read an Excel file which has following columns: invoiceid, locationid, timestamp, customerid, discount, tax,total, subtotal, productid, …

Modifying the weights and biases of a restored CNN model in TensorFlow

I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, Ive restored a pre-trained model, and I need to modify the weights and biases of o…

Flask SQLAlchemy paginate over objects in a relationship

So I have two models: Article and Tag, and a m2m relationship which is properly set.I have a route of the kind articles/tag/ and I would like to display only those articles related to that tagI have so…

generating correlated numbers in numpy / pandas

I’m trying to generate simulated student grades in 4 subjects, where a student record is a single row of data. The code shown here will generate normally distributed random numbers with a mean of 60 …

AttributeError: list object has no attribute split

Using Python 2.7.3.1I dont understand what the problem is with my coding! I get this error: AttributeError: list object has no attribute splitThis is my code:myList = [hello]myList.split()

Managing multiple Twisted client connections

Im trying to use Twisted in a sort of spidering program that manages multiple client connections. Id like to maintain of a pool of about 5 clients working at one time. The functionality of each clien…

using a conditional and lambda in map

If I want to take a list of numbers and do something like this:lst = [1,2,4,5] [1,2,4,5] ==> [lower,lower,higher,higher]where 3 is the condition using the map function, is there an easy way?Clearly…

Tkinter: What are the correct values for the anchor option in the message widget?

I have been learning tkinter through Message widget in Tkinter at Python Courses and Tutorials. I keep getting an error when I add the anchor option with the options presented on the site. I am being t…