How to create process in Linux using fork system call ?

Below is simple process creation program using fork system call, fork return childs process Id in main/parent process and return 0 in child 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: we can use perror\n");
                        perror("fork");
                        exit(1);
                case 0:
                        printf("hello world\n");
                        exit(0);
                default:
                        wait(&child_status);
        }
        printf("continueing parent process execution\n");
        return 0;
}
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply