Fork() Exercise

Example 1


Original

int val;

val=fork(); //val>0
#when fork() is called the OS creates a new process that is a copy of the calling process. 

if(val>0)
cout <<"Parent" <<endl;
else
cout <<"Child" <<endl;
//output Parent

Child

int val;
val=fork();

//Child starts from here
if(val>0) //val is 0
cout <<"Parent" <<endl;
else
cout <<"Child" <<endl;
//output Child

output Child \n Parent

Another Example:
parent spawns 2 processes

fork();
fork();
cout<<"*"

child 1

fork();
cout<<"*"

child 2

cout<<"*"

child 1 then spawns a new process

cout<<"*"

output ****

Process Tree

Pasted image 20250304181528.png

fork() //A
cout <<"1"<<endl;

if(!fork()) //B
	cout <<"2"<<endl;
else
	cout <<"3"<<endl;
cout <<"4"<<endl;

Pasted image 20250304184304.png

Example 2


int val = fork(); //A

if(val)
{fork(); //B
cout << "1" endl;}
else
cout<<"2"<<endl;

fork(); //C 
cout<<"3"<<endl;

A fork()

//int val = fork(); //A
if(val)
{fork(); //B
cout << "1" endl;}
else
cout<<"2"<<endl;

fork(); //C 
cout<<"3"<<endl;

B fork()

//{fork(); //B
cout << "1" endl;}
else
cout<<"2"<<endl;

fork(); //C 
cout<<"3"<<endl;

C fork()

//fork(); //C 
cout<<"3"<<endl;

Pasted image 20250311183228.png

Example 3 With Exec


int val - fork(); //A

if(val)
{
	exec("no_output_prog"); 
	fork();
	fork();
}

fork(); //B
cout <<'*';

fork A

//int val - fork(); //A
//val is 0, 
if(val)
{
	exec("no_output_prog"); 
	fork();
	fork();
}

fork(); //B
cout <<'*';

fork B

//fork(); //B
cout <<'*';

Pasted image 20250313175502.png

Example 4

if(fork())
{
wait();
cout<<'1'<<endl;} 
}
else 
cout <<'2'<<endl;

Pasted image 20250318174217.png

Wait() is expected to pause the calling process until child terminates