tags: os operating-system process architecture is_child_of: process

Process Creation

A process is created by following events:

  1. System initialisation
  2. Running process calling process creation system call
  3. User launching a process
  4. Starting a batch job

A process is created by using system calls provided by operating system. fork is the system call used to create a clone of an existing process.

Taking the example of shell, when we a run a command following things happen:

  1. It forks a child process using fork system call
  2. Child process copies the file descriptors of the parents to manipulate stdin, stdour and stderr
  3. Child process then execute execve() system call to change the process image to that command. It means that instead of executing the child process code, the code of that command will be executed

A simple shell using this theory.

import os
 
 
def read_command() -> tuple:
    user_input = input("> ")
    return tuple(user_input.strip().split(' '))
 
 
while True:
    command, *argv = read_command()
    env = {'PATH': os.environ['PATH']}
    pid = os.fork()
 
    if pid == 0:
        os.execve(command, [command, *argv], env)
    else:
        chid_pid, status =\
         os.waitpid(pid, os.WUNTRACED)
 

I’m not doing duplication of file descriptors in this example. However this duplication can be done using dup2 system call.