-- Back to Index --
Process Lifecycle stages are listed as below:
Forking is the common method of creating new process. In Python, you use os.fork() whereas in Perl, you use fork().
During execution stage, the worker() subroutine runs the child process, while the parent process waits for the child to finish using os.waitpid() in Python and waitpid() in Perl.
Normal termination is when a process can terminate normally by completing its execution or by calling an exit function.
Abnormal termination is when a process may terminate abnormally due to an error or a signal (e.g. SIGKILL), or being killed by another process.
In Python, in the child process, you use os._exit(0) to terminate and exit(0) in Perl.
The operating system releases resources and cleans up the process table entry.
Processes can communicate and synchronize using various mechanisms e.g. pipes, message queues, shared memory, and sockets. It can handle signals for various events.
Let's show in Perl first:
#!/usr/bin/env perl use v5.38; sub worker { say "\tChild process (PID: $$) started."; sleep(2); say "\tChild process (PID: $$) finished."; exit(0); } sub parent { say "Parent process (PID: $$) started."; my $pid = fork(); if ($pid == 0) { worker(); } else { say "\tChild process (PID: $pid) created."; waitpid($pid, 0); say "Parent process (PID: $$) finished."; } } parent(); Run the code:
$ perl process.pl Parent process (PID: 7654) started. Child process (PID: 7655) created. Child process (PID: 7655) started. Child process (PID: 7655) finished. Parent process (PID: 7654) finished. $ In Python, we would do something like below:
#!/usr/bin/env python3 import os import time def worker(): print(f"\tChild process (PID: {os.getpid()}) started.") time.sleep(2) print(f"\tChild process (PID: {os.getpid()}) finished.") os._exit(0) def parent(): print(f"Parent process (PID: {os.getpid()}) started.") pid = os.fork() if pid == 0: worker() else: print(f"\tChild process (PID: {pid}) created.") os.waitpid(pid, 0) print(f"Parent process (PID: {os.getpid()}) finished.") if __name__ == "__main__": parent() Run the code now:
$ py process.py Parent process (PID: 7668) started. Child process (PID: 7669) created. Child process (PID: 7669) started. Child process (PID: 7669) finished. Parent process (PID: 7668) finished. $ -- Back to Index --