Lab – Processes and Threads

Write a program that does the following:

  • When the program start fork a new child process. The father process should wait for the child process to finish.
  • The child process main thread should spawn 5 additional threads.
  • Each thread should print: “I am thread number n” and terminate.
  • The child process main thread should wait for all it’s threads to terminate. It should then print “Bye” and exit.
  • When the child exists, the father should print “Goodbye” and exit

reference:

  • To create a child process use – fork   (man 2 fork)
  • To wait for a child process use wait (man 2 wait)
  • to create a new thread use pthread_create (man pthread_create)
  • to wait for a child thread to exit use pthread_join (man pthread_join)

 

Task 2

  • build 5 processes that runs forever – each one print message every 5 seconds 
  • the main process create its children and wait until they die
  • if a child process die – the main create it again
#include<stdio.h>

void task1(void)
{

	while(1){
		puts("task1");
		sleep(5);
		}
}	
void task2(void)
{

	while(1){
		puts("task2");
		sleep(5);
		}
}	
void task3(void)
{

	while(1){
		puts("task3");
		sleep(5);
		}
}	
void task4(void)
{

	while(1){
		puts("task4");
		sleep(5);
		}
}	
void task5(void)
{

	while(1){
		puts("task5");
		sleep(5);
		}
}	


void main(void)
{
	int id,i,s;
	
	for (i=0;i<5;i++)
	{
		id = fork(); 
		if(id == 0)
		{
			// todo: call a  function task[n]
			exit(0);
		}
		
	}
	
	while(1)
	{
		//TODO: wait and restore a dead process
	}
		
}

 

  • run the app – you will see a message every 5 second 
  • open a new terminal 
  • use ps aux to see all tasks – look at the process id 
  • use kill -9 [pid] to kill one task
  • look at the output to see it restarted