Question

Answer this question Properly Please find out how many processes and how many threads are created:...

Answer this question

Properly

Please find out how many processes and how many threads are created:

                             pid_t pid;

            pid = fork();

            if (pid == 0) { /* child process */

                  fork();

                  thread_create(...);

}

fork();

a) Write working codes from the pseudo-code above. Add appropriate codes to ensure that you have time to observe processes and threads using ‘top’ and ‘H’ keystroke.

b) Draw a simple diagram showing the processes and threads in their parent/child relationship.

c) Take snapshots of your code’s execution and your observation of the processes/threads.

d) Explain why your code created this number of processes and threads

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

void *work(void * parm) {
printf("Thread Work function\n");
}

int main ()
{
pid_t child_pid1, child_pid2;
pthread_t cThread;
  
printf ("the main program process ID is %d\n", (int) getpid());
  
child_pid1 = fork () ;
// AT this point 2 processes are present
if (child_pid1 == 0) {
printf ("this is the child process1, with id %d\n", (int) getpid ());
  
int *param = (int *)malloc(2 * sizeof(int));
param[0] = 123;
param[1] = 456;
  
// Only 1 process can reach the below code
child_pid2 = fork () ;
// at this time, Again 2 process will appear
  
// So now 2 processes, each will create a new thread..
pthread_create(&cThread, NULL, work, param);

  
if (child_pid2 > 0)
{
printf ("this is child process1 after forking its child\n");
}
else if (child_pid2 == 0) {
printf ("this is the child process2, with id %d\n", (int) getpid ());
}
}
  
// 4 processes will reach here..
fork();
// Total 8 processes will reach at this stage
  

return 0;
}

/// Comments inline.. I do not have a linux system to run the program and check the output.. because system calls like fork will not work on windows system.

Add a comment
Know the answer?
Add Answer to:
Answer this question Properly Please find out how many processes and how many threads are created:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT