Child Process Creation Fork
Child Process Creation Fork
#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 */
}