23 December 2017

Process Management in Python - os.exec

This is continuation of the previous post - Process Management in Python - os.fork()

In Linux, running a command from the shell is a two-step process. The shell first creates a process using fork (posted earlier) and overlays a new program using "exec". For example, when you want to run the command "ls" from the shell - the shell forks a copy of its own and immediately loads the binary of "ls" and starts the execution again.


Beware, you cannot find a function exec() but rather it is a family of functions with names such as - execl, execle, execlp, execv. The functions are almost same and they differ only in parameters that are being passed. I have used one such functions in the following code. When you run this code, you should see a directory listing - the current process upon the successful calling of exec, loads "ls" and executes it. Once "ls" is executed, it exits (like it normally used to do)

As an experiment, you can do fork to create a child process and in the child process execution flow, you can overlay a new program.

Refer the Code in GIT Hub

Try running this script from Linux shell and see the output. Do not forget to share, like, comment if you like this post :-)