How to create process in Linux using fork system call ?

Below is simple process creation program using fork system call, fork return child’s process Id in main/parent process and return 0 in child process. Fork duplicates the current (parent) process as new (child) process, creating another new entry in the process table with many of the same attributes/variables as the parent process.

Once the child process is completed, it normally reports its status to the parent process, now if a parent process tries to complete even before child is finished, we need to wait for child process to finish, otherwise parent process will terminate before child finished, resulting child becoming parentless, for which process 0 or init becomes the parent. This process, for whom parent died before its own completion is called “Orphan” process.

int main(int argc, char **argv) {
        pid_t child_pid;
        int child_status;

        child_pid = fork();
        switch (child_pid) {
                case -1:
                        printf ("error: Some error occurred while creating the process\n");
                        perror("fork");
                        exit(1);
                case 0:
                        printf("hello world: I am a child process\n");
                        exit(0);
                default:
                        printf("Hi There! You are continuing with parent process !\n");
                        wait(&child_status);
        }
        printf("continuing parent process execution\n");
        return 0;
}

Zombie process getting created due to coding mistakes is a very common things when you work with creating process’s hence you can read our another posts as well at “How to avoid zombie process in Linux ?” and “What is Zombie process and How to create zombie process in Linux ?”


lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


Leave a Comment

Android Android Build system Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded