Write a program for process creation using C. (Use of gcc compiler).
// Child process Creation Fork.c unix program
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int pid;
/* fork another process */
pid = fork();
if (pid < 0) { /* error occurred */
printf( "Fork Failed");
exit(-1);
}
else if (pid == 0) { /* child process */
execlp("/bin/ls","ls",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
wait(NULL);
printf ("Child Complete");
exit(0);
}
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main ()
{
int pid;
printf ("I'm the original process with PID %d and PPID %d.\n",
getpid (), getppid ());
pid = fork (); /* Duplicate. Child and parent continue from here */
if (pid != 0) /* pid is non-zero, so I must be the parent */
{
printf ("I'm the parent process with PID %d and PPID %d.\n",
getpid (), getppid ());
printf ("My child's PID is %d\n", pid);
}
else /* pid is zero, so I must be the child */
{
printf ("I'm the child process with PID %d and PPID %d.\n",
getpid (), getppid ());
}
printf ("PID %d terminates.\n", getpid () ); /* Both processes execute this */
}
Output: gcc fork.c
$ ./a.out
I'm the original process with PID 23549 and PPID 18774.
I'm the parent process with PID 23549 and PPID 18774.
My child's PID is 23550
PID 23549 terminates.
I'm the child process with PID 23550 and PPID 23549.
PID 23550 terminates.