How to Create a Process using C Programming Language? [using fork() function] - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

How to Create a Process using C Programming Language? [using fork() function]

Share This
If we run a program, a process is created. If you check the process list in your operating system, you get an entry by the process name. Sometimes, a scenario demands multiple process creation of the same program. Specifically, a program creates another program from within it. In this tutorial, we will discuss how to create a duplicate process from within a process. 

In a Linux environment, you can create a process by calling the fork() function, which duplicates the current process. Hence, the new process contains the same attributes as the main process but has its own data space, file descriptors, and environment.

The fork() function returns 0 if it's successful, it returns -1 if there is an error, like insufficient virtual memory, number of child processes exceeding its permissible limit, etc.
Source code for process creation
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { pid_t pid; char *msg; int n; printf("fork program is starting...\n"); pid = fork(); switch(pid) { case -1:perror("fork failed..."); exit(1); case 0: msg = "This is the child process!"; n = 5; break; default:msg = "This is the parent process!"; n = 2; break; } for(; n > 0; n--) { puts(msg); sleep(1); } exit(0); }


Take a look at the output. The main process gets completed before the child process is completed. We can also restrict parent process termination before all the children are terminated. We will discuss it later.


In the following example program, we will discuss how parent and child process ids can be managed.

Source code
#include <unistd.h> #include <sys/types.h> #include <errno.h> #include <stdio.h> #include <sys/wait.h> #include <stdlib.h> int main() { pid_t childProcId; int returnVal; int status; childProcId = fork(); if (childProcId >= 0) { if (childProcId == 0) { printf("It's child process!\n"); printf("Process ID (PID) of child: %d\n", getpid()); printf("Parent's PID is: %d\n", getppid()); printf("The value of childProcId is: %d\n", childProcId); sleep(1); printf("Enter an exit value (0 to 255): "); scanf("%d", &returnVal); printf("Goodbye!\n"); exit(returnVal); } else { printf("It's parent process!\n"); printf("Process ID (PID) of parent: %d\n", getpid()); printf("The value of childProcId is %d\n", childProcId); printf("Waiting for child to exit.\n"); wait(&status); printf("Child's exit code is: %d\n", WEXITSTATUS(status)); printf("Goodbye!\n"); exit(0); } } else { perror("fork"); exit(0); } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.