Python - os.fork()

版权声明:转载请注明出处 https://blog.csdn.net/qq_42292831/article/details/89319355

主进程fork返回的是子进程的PID,子进程fork返回0

  • time.sleep()
  • os.fork()
  • os.getpid()

PID:process_identity

UID:User_Identity

R:RUN 进程处于运行状态

S:SLEEP 进程休眠状态

X:ERROR 进程Die但是没有被移除队列


Python程序后台运行:python xxx.py &



# ps -u
# ps -l
# kill PID


import time
import os

try:
	number = 10
	pid=os.fork()    #主进程结束之后,子进程会从这里开始执行
	print("***********----***********")
	if pid == 0:
		print("This is a child process! PID:",os.getpid())
		number-=1
		time.sleep(10)    #虽然主进程结束了,但是子进程并没有结束
		print(number)
	else:
		print("This is a parent process! PID:",os.getpid())    #到这里主进程就已经结束了,接下来读取子进程(后台)
except OSError as e:
	print(e)

猜你喜欢

转载自blog.csdn.net/qq_42292831/article/details/89319355