0% found this document useful (0 votes)
16 views2 pages

Child Process Creation Fork

The document provides a C program demonstrating process creation using the fork system call. It includes two examples: one that executes the 'ls' command in the child process and another that prints the process IDs of the parent and child. The program illustrates the behavior of parent and child processes, including their termination messages.

Uploaded by

Binod Tharu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Child Process Creation Fork

The document provides a C program demonstrating process creation using the fork system call. It includes two examples: one that executes the 'ls' command in the child process and another that prints the process IDs of the parent and child. The program illustrates the behavior of parent and child processes, including their termination messages.

Uploaded by

Binod Tharu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

You might also like