Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C with Linux. Help with fork() and wait() system calls. Goals The purpose of thi

ID: 3846836 • Letter: C

Question

C with Linux. Help with fork() and wait() system calls.

Goals The purpose of this lab is to help you learn about fork0 and wait() system calls in C. Tasks Task 1 1. define a function to carry out the task corresponds to a child process within the operating system as: (a) this function should use a system call to get its corresponding process identification. (b) this function should print the obtained process ID on the console. (c) this function prints either 'a' or 'b'. Whether it should print 'a' or 'b' should be determined by one of the arguments of this function. (d) this function should at the end use a library call that cause normal process termination. 2. the main function create two separate child processes as: (a) the main function should call a system call twice to create two separate child processes (b) by using if statements, the main function should call the function that was defined for the child processes by given this function appropriate inputs. This function should be called twice for each of the child processes. (c) by using a system call, this function should wait for both of its child processes to terminate. (d) print an end of line character at the end

Explanation / Answer

Question 1: Program in c++ is given below:

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

void *PrintThreadId(void *thread_id) {
   long* t_id;
   t_id = (long*)thread_id;
   cout << "Thread ID :" << *t_id << endl;
   pthread_exit(NULL);
}

int main () {
   pthread_t new_threads[2];
   int rsp;
   int i;
  
   for( i=0; i < 2; i++ )
   {
      rsp = pthread_create(&new_threads[i], NULL, PrintThreadId, (void *)i);
      
      if (rsp){
         cout << "Error in thread creation," << rsp << endl;
         exit(-1);
      }
   }
  
   pthread_exit(NULL);
}