Last active
March 15, 2020 01:54
-
-
Save pedrominicz/99e6df3c813d6a5c90f0a466ba4a8b41 to your computer and use it in GitHub Desktop.
`fork` and `exec` in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
# `fork` current process. On success, the child's PID is returned to the parent | |
# and `0` is returned to the child. On failure, `-1` is returned and no process | |
# is created. | |
pid = os.fork() | |
if pid == -1: | |
os.exit(1); | |
# At this point there are two processes running. The parent will not enter the | |
# `if` statement and the child will. | |
if pid == 0: | |
# In the `exec` family of functions, functions with `l` are variadic (i.e. | |
# take `argv` in multiple arguments) and functions with `p` search for the | |
# executable file in the `PATH` environment variable. | |
# | |
# Note that `'echo'` is repeated twice because the first one refers to the | |
# process to execute and the second one to the first argument passed to the | |
# process, i.e. `argv[0]`. | |
# | |
# Since only the child enters the `if` statement, only the child becomes an | |
# `echo` process. | |
os.execlp('echo', 'echo', 'hello world') | |
# Suspend the execution of the parent until one of its children terminates. In | |
# this case, the only child is bound to execute `echo`. | |
os.wait() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment