Write a program (using fork() and/or exec() commands) where parent and child execute: a) same program, same code. b) same program, different code. - c) before terminating, the parent waits for the child to finish its task.


#include<iostream>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
using namespace std;

int main()
{
    pid_t pid;
    pid=fork();
    if(pid<0)
    {
        cout<<"this is a process";
    }
    else
    {
        cout<<"process continues";
    }
    return 0;
}


(b) same program, different code

#include<iostream>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
using namespace std;

int main()
{
pid_t pid;
pid=fork();
if(pid<0)
{
cout<<"new process not entered";
}
else if(pid==0){
cout<<"Child process";
}
else
cout<<"parent process";
return 0;
}


(c) different programs

#include<iostream>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
using namespace std;

int main(){
pid_t pid;
pid=fork();
if(pid<0){
cout<<"No process entered";
}
else if(pid==0){
execlp("/bin/ls","ls",NULL);
cout<<"child process";
}
else {
cout<<"parent process";
}
return 0;
}


(d) before terminating, the parent waits for the child to finish its task

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

int main(){
pid_t pid;
pid=fork();
if(pid<0){
cout<<"No process entered";
}
else if(pid==0){
execlp("/bin/ls","ls",NULL);
cout<<"child process";
}
else {
wait(NULL);
cout<<"parent process";
}
return 0;
}

Comments