Python Forking Tutorial

Advertisement

Advertisement

Introduction

When you fork a process with os.fork(). Note this will not work with the latest versions of Python in Windows. You will want to use Python's multiprocessing library for that.

Duplicate the current process

To split the process in to two duplicates, you can use os.fork() to call the fork system call.

import os

# Duplicate the current process in to another process
new_pid = os.fork()  # Will return 0 if child process

if new_pid == 0:
    print(f"My pid is {new_pid}, I am a child process!")
else:
    print(f"My pid is {new_pid}. I am the parent!")

Get process id

You might want to get the process id of a running process. You can get it with os.getpid().

import os

pid = os.getpid()
print(f"My pid is {pid}")

Kill a process

To kill a process using its process id, use os.kill(). You must pass it the pid as well as the signal you want to send to the process. This example will send the SIGINT signal (like a CTRL-C event) to itself.

import os
import signal

my_pid = os.getpid()

# Kill a process using its pid
os.kill(my_pid, signal.SIGINT)

Conclusion

After reading this guide you should understand how to fork a process in Python, check if a process is a child, and kill a process.

References

Advertisement

Advertisement