3 Os
3 Os
3 Os
AIM: Write a C program to create child process in linux using the fork system call. From
child process obtain process ID of both child and parent by using getpid and getppid system
call.
THEORY:
getpid() :
Returns the process ID of the calling process. This is often used by routines that
generate unique temporary filenames.
Syntax: pid_t getpid(void);
Return type: Returns the process ID of the current process. It never throws any error
therefore is always successful.
getppid():
Returns the process ID of the parent of the calling process. If the calling process was
created by the fork() function and the parent process still exists at the time of the
getppid function call, this function returns the process ID of the parent process.
Otherwise, this function returns a value of 1 which is the process id for init process.
Syntax: pid_t getppid(void);
Return type: getppid() returns the process ID of the parent of the current process. It
never throws any error therefore is always successful.
ALGORITHM:
1. Declare variable i.
2. for i = 1 to MAX_COUNT.
3. If i%2==0 Then Print value of i.
4. i=i+1
5. Print “Child process ID”.
6. Print (getpid())
7. END For
8. Print “Child process is done”
1. Declare variable i.
2. for i = 1 to MAX_COUNT.
3. If i%2!=0 Then Print value of i.
4. i=i+1
5. Print “Parent process ID”.
6. Print (getppid())
7. END For
8. Print “Child process is done”
CONCLUSION: Hence created a child process from a parent using fork () system call and
also tested its creation. Therefore the created processes also differentiated using getpid ()
and getppid () system calls.
PROGRAM
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#define MAX_COUNT 10
void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */
void main()
{
pid_t pid;
if (pid == 0)
ChildProcess();
else
ParentProcess();
}
void ChildProcess(void)
{
int i;
for (i = 1; i <= MAX_COUNT; i++)
{
if(i%2==0)
{
printf("%d \n",i);
}
}
printf(" This line is from child, value = %d\n", i);
printf("child process: %d \n",getpid());
printf(" *** Child process is done ***\n");
}
void ParentProcess(void)
{
int i;
OUTPUT:
1
3
5
7
9
This line is from parent, value = 11
parent process: 2963
*** Parent is done ***
2
4
6
8
10
This line is from child, value = 11
child process: 3069
*** Child process is done ***