Forking in *nix System using C and Python


[The fork() system call will spawn a new child process which is an identical process to the parent except that has a new system process ID. The process is copied in memory from the parent and a new process structure is assigned by the kernel. The return value of the function is which discriminates the two threads of execution. A zero is returned by the fork function in the child’s process.]

The fork() is one of the important methods that allows multiprocess/multitasking in Linux operating system. The following C code can be compiled in Linux.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <unistd.h>
 
int main() {
    pid_t pid;
    switch (pid = fork())
    {
        case -1: 
            perror("fork failed");
            break;
        case 0: // child process
            execl("/bin/ls","ls","-1",(char *)0);
            perror("exec failed"); // if reaches here, it means failure
            break;
        default:
            wait((int *)0); // process synchronization in the parent thread
            printf ("ls completed\n");
            exit(0);
    }
}
#include <unistd.h>

int main() {
	pid_t pid;
	switch (pid = fork())
	{
		case -1: 
			perror("fork failed");
			break;
		case 0: // child process
			execl("/bin/ls","ls","-1",(char *)0);
			perror("exec failed"); // if reaches here, it means failure
			break;
		default:
			wait((int *)0); // process synchronization in the parent thread
			printf ("ls completed\n");
			exit(0);
	}
}

system() executes a new process and only gives control back to your application process when it is done. execl() in the example above replaces the current process image. It can be used in one of two ways: With a fork(), the execl() replaces the child process allowing your main process (the parent) to continue untouched. Without fork(),
execl() effectively replaces your parent process and you can’t go back.

In Linux, the python script allows forking processes as well. The following is an easy example that is quite similar to the C example above.

#!/usr/bin/env python

import os

def the_fork():
    child_pid = os.fork()
    if child_pid == 0:
        print "Child Process: PID %s" % os.getpid()
    else:
        print "Parent Process: PID %s" % os.getpid()

if __name__ == "__main__":
    the_fork()

However, the above Python script is not supported on Windows platforms, Windows doesn’t provide functionality that is exactly like fork() on other systems. To do multiprocessing on Windows, you can use the threading or multiprocessing modules.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
404 words
Last Post: A SleepSort using Multiprocessing in BASH
Next Post: Execute External Programs, the Python Ways.

The Permanent URL is: Forking in *nix System using C and Python

Leave a Reply