Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating child process using fork() in Python
The fork() function in Python allows you to create child processes by duplicating the current process. This is a fundamental concept in Unix-like systems for process management and multithreading environments.
When fork() is called, it creates an exact copy of the calling process. The return value helps distinguish between parent and child processes: 0 indicates the child process, a positive value indicates the parent process (containing the child's PID), and a negative value indicates an error occurred.
Understanding fork() Return Values
The fork() function returns different values depending on which process you're in ?
- Child process: Returns 0
- Parent process: Returns the child's process ID (positive integer)
- Error: Returns a negative value
Using os.fork()
The most common way to use fork() is through the os module ?
import os
def create_child_process():
pid = os.fork()
if pid > 0:
print("Parent process ID:", os.getpid())
print("Child process ID:", pid)
elif pid == 0:
print("Child process ID:", os.getpid())
print("Parent process ID:", os.getppid())
else:
print("Fork failed")
# Driver code
create_child_process()
The output will show both parent and child process IDs ?
Parent process ID: 8023 Child process ID: 8024 Child process ID: 8024 Parent process ID: 8023
Using pty.fork()
The pty module provides an alternative way to fork processes with pseudo-terminal support ?
import pty
import os
def create_pty_process():
try:
pid, fd = pty.fork()
if pid == 0:
# Child process
print("Child process ID:", os.getpid())
else:
# Parent process
print("Parent process ID:", os.getpid())
print("Child process ID:", pid)
except OSError as e:
print("Fork failed:", e)
create_pty_process()
Parent process ID: 12508 Child process ID: 12509 Child process ID: 12509
Key Differences
| Method | Module | Additional Features | Platform |
|---|---|---|---|
os.fork() |
os | Basic process forking | Unix-like systems |
pty.fork() |
pty | Pseudo-terminal support | Unix systems only |
Important Notes
-
fork()is only available on Unix-like systems (Linux, macOS) - Both parent and child processes execute the code after the
fork()call - The
ptymodule is highly platform-specific and requires Unix systems - Always handle potential errors when using
fork()
Conclusion
The fork() function is essential for creating child processes in Python on Unix systems. Use os.fork() for basic process creation and pty.fork() when you need pseudo-terminal functionality.
