PCS 511(S) Operating System & Computer Networks Lab
Problem Statement 8:
a. Write a program to create a child process using system call fork().
b. Write a program to print process ID's of parent and child process. That is parent should
print its own and its child process ID while child process should print its own and its
parent process ID. (use getpid(), getppid()).
c. Write a program to create child process. Make sure that parent process waits until child
has not completed its execution. (use wait(), exit()).
Manual 8.a
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(){
pid_t q;
q= fork();
if (q<0)
{
printf("error");
}
else if(q= =0){
printf("child %d\n", getpid());
printf("parent is %d\n", getppid());
}
else{
printf("parent %d\n", getpid());
printf("child is %d\n", q);
}
printf("common \n");
return 0;
}
Manual 8.b
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = fork(); // create child process
if (pid < 0) {
// fork failed
printf("Fork failed!\n");
}
else if (pid = = 0) {
// child process
printf("Child Process:\n");
printf(" My PID is %d\n", getpid());
printf(" My Parent PID is %d\n", getppid());
}
else {
// parent process
printf("Parent Process:\n");
printf(" My PID is %d\n", getpid());
printf(" My Child PID is %d\n", pid);
}
return 0;
}
Manual 8.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid1, pid2;
// First child
pid1 = fork();
if (pid1 = = 0) {
printf("Child 1: My PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(2);
printf("Child 1: Finished execution\n");
exit(0);
}
else {
wait(NULL);
printf("Parent: Child 1 has finished (PID = %d)\n", pid1);
// Second child
pid2 = fork();
if (pid2 = = 0) {
// Child 2 code
printf("Child 2: My PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(4);
printf("Child 2: Finished execution (my parent may have exited)\n");
exit(0);
}
else {
// Parent exits immediately (does not wait for Child 2)
printf("Parent: Exiting now before Child 2 completes...\n");
exit(0);}}}
+++++++