Skip to content

Instantly share code, notes, and snippets.

@manwar
Last active March 1, 2025 16:38
Show Gist options
  • Select an option

  • Save manwar/ea245ff7df5b3e43d2f30eb7daef84da to your computer and use it in GitHub Desktop.

Select an option

Save manwar/ea245ff7df5b3e43d2f30eb7daef84da to your computer and use it in GitHub Desktop.
Process Lifecycle in Perl and Python.

-- Back to Index --


Process Lifecycle stages are listed as below:

#1: Creation


Forking is the common method of creating new process. In Python, you use os.fork() whereas in Perl, you use fork().

#2: Execution


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.

#3: Termination


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.

#4: Cleanup


The operating system releases resources and cleans up the process table entry.

#5: IPC / Signals


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:

[Source Code]

#!/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:

[Source Code]

#!/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 --


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment