Question

In: Computer Science

Based on the below code: Answer the following questions and explain your answers: i)Presume that the...

Based on the below code: Answer the following questions and explain your answers:

i)Presume that the code is instantiated in a process and it has JUST returned from its own call to fork() and there is now a clone of that process that is itself “just about” to pick up execution. Where will the clone child pick up its execution?

ii)How does the clone child know it’s a clone? How does the parent process know it is not a clone, or at least not the clone if just made by calling fork()?

iii)Compile and run the program from the command line. Scroll through the whole history of outputs and describe how that two processes (original and clone) seem to be writing to the same terminal. Do you notice anything that isodd? Explain why you might be seeing this oddness.

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

int main(int argc, char **argv)

{ pid_t fork_returned_pid;
int count;

fork_returned_pid = fork();

if (fork_returned_pid < 0)
{ printf("The fork() didn't work! Terminate\n");
exit (0); }

for (count = 0; count < 1000; count++)
{ if (fork_returned_pid == 0)
printf(" child says: count = %d\n", count);
else
printf("parent says: count = %d\n", count);
}
}

Solutions

Expert Solution

Please find the properly indented code which will help to understand the program flow.

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

int main(int argc, char **argv)

{ 
    pid_t fork_returned_pid;
    int count;

    fork_returned_pid = fork();

    if (fork_returned_pid < 0)
    { 
        printf("The fork() didn't work! Terminate\n");
        exit (0); 
        
    }

    for (count = 0; count < 1000; count++)
    { 
        if (fork_returned_pid == 0)
            printf(" child says: count = %d\n", count);
        else
            printf("parent says: count = %d\n", count);
    }
}

Question 1 :

Child clone will pick up its execution after the fork process. In our example, child process will start execution from line 4 of int main function.

Question 2 :

Below line is crucial to understand the program.

fork_returned_pid = fork();

When we run the program, it runs in main_thread ( let's assume pid = 5 ). When the above line is executed, a new thread is created. Let's call it new_thread ( let's assume pid = 6750 ).  

The fork returns the pid of the child in the parent process, and return 0 in the child process

According to the statement above,

In Main Thread

fork_returned_pid = fork()         //  In main_thread , after execution of this line, fork_returned_pid = 6750

In Child Thread

fork_returned_pid = fork()         //  In child_thread , after execution of this line, fork_returned_pid = 0

From that line, both the threads will execute indpendently.


Question 3 :

As this is multi-threading program, different compilers may show different output. Even on single compiler running the program multiple times may show different output. Why ? Because, Understand the below steps
Let's say CPU started executing main_thread.
CPU created new_thread.
CPU executed few lines from main_thread.
CPU may switch to new_thread. and execute few more statements in the new_thread.
Then again CPU may switch back to main_thread. and this goes on untill both of those are properly executed.

You as a User can't predict how many statements will be executed by CPU if it is inside main_thread or if it is inside new_thread.

Why Such Odd behaviour ? Why CPU don't guarantee how many statements will be executed ?

Because Multi-threading is not meant to guarantee order of execution among process. Multi threading is meant to be used to run two independelty programs. THe focus is to complete the both programs, not the order in which program gets executed. We need multi threading so CPU doesn't sit Ideal. If we decide the CPU should run first thread for x amount of lines, it clearly voids the advantage of multithreading.

How to run and analyse the programs

// Save the above code as first.c 

// Compile the given file on gcc compiler. Successful execution of this command creates object file named 'first'
gcc first.c

// Run the object file created in above step.
gcc -o first first.c


Try to run this object file multiple times, you may see different output everytime you run. 

Screenshots of program at different instance of time :

In Below screenshot we can see, both the threads are switched by CPU after execution of one Single statement. So we get output from parent and child alternatively.

In Below Screenshot you can see only child is getting executed.

In Below screenshot you can see only parent is getting executed.

So order totally depends upon CPU which can't be predicted.


Related Solutions

Understand the code and explain the code and answer the questions. Type your answers as comments....
Understand the code and explain the code and answer the questions. Type your answers as comments. #include #include using namespace std; // what is Color_Size and why it is at the end? enum Color {        Red, Yellow, Green, Color_Size }; // what is Node *next and why it is there? struct Node {        Color color;        Node *next; }; // explain the code below void addNode(Node* &first, Node* &last, const Color &c) {        if (first == NULL)...
Please answer the below questions ( I need answers for all the below questions). Thank you...
Please answer the below questions ( I need answers for all the below questions). Thank you True or False Write true if the statement is true or false if the statement is false. _______ The heart consists mainly of muscle. _______ Blood pressure is highest in veins. _______ Atherosclerosis is the buildup of plaque inside arteries. _______ Platelets are blood cells that fight infections. _______ Peripheral gas exchange takes place in the lungs. _______ Food travels from the mouth to...
Answer the following questions based on the reaction below. Report all answers to three significant figures....
Answer the following questions based on the reaction below. Report all answers to three significant figures. K2SO4(aq) + Sr(NO3)2(aq) → SrSO4(s) + 2KNO3(aq) The concentration of K2SO4 is 0.222 M at the start of the reaction, and 0.135 M after 122 seconds. The initial concentrations of the products are zero. 1. What is the average rate of reaction (in M/min) over this time period? 2. What is the average rate of change (in M/min) of K2SO4 in the first 122...
Answer true or false to the following questions please explain your answers and answer all please  ...
Answer true or false to the following questions please explain your answers and answer all please   1.The cytoplasmatic side of the integral membrane proteins is often glycosylated. 2. Cholesterol is more enriched at the outer leaflet of the plasma membrana 3.Inner leaflet of the plasma membrane is enriched with glycolipids. 4.Membrane proteins that pomp ions in and out of the cell have specific Km values. 5. A symport would function as an antiport if its orientation in the membrane were...
Answer the following questions below in your own words (NO PLAGIARISM) A- Answer the following questions...
Answer the following questions below in your own words (NO PLAGIARISM) A- Answer the following questions (300 words): Reflect on your experiences realizing your gender: How did you learn about your gender? What happened? What gender “rules” were you aware of in this experience? B- Answer the following questions (300 words) Reflect on your experiences learning about sexuality: Where did you learn about sexuality? What did you learn? How was it gendered? What do you think it should include for...
​​​​​​For my Accounting project I need to answer the following questions: 1. Based on your analysis...
​​​​​​For my Accounting project I need to answer the following questions: 1. Based on your analysis and company research would you, as a bank-lending officer, approve a 5-year loan for this company? If so, how much would you approve the loan for and for what purpose? Would you require security or collateral? Explain your reasoning. As a bank-lending officer, I would approve a 5 year short term loan for Johnson and Johnson. 2. Provide a recommendation as to whether an...
Answer the following questions. Your answers should address all parts of the questions and be approximately...
Answer the following questions. Your answers should address all parts of the questions and be approximately 300-400 words each. Make sure to thoroughly support all answers with accurate details and relevant evidence from the textbook and other resources. 1. Several coworkers are in the lunchroom on their lunch break. Sam and his friend George are having a rather loud conversation about the party they attended over the past weekend. George relates a joke that he heard at the party; it...
As you answer these questions, be sure that you EXPLAIN YOUR ANSWERS IN DETAIL AND SHOW...
As you answer these questions, be sure that you EXPLAIN YOUR ANSWERS IN DETAIL AND SHOW YOUR CALCULATIONS. Remember you are showing off how much you know about economics and one or two sentences shows me you don’t know very much. Question One: Fiscal Policy Assume the United States economy has the following: • GDP is $18,500 billion down from $19,350 billion nine months ago. • Unemployment is at 6.8% up from 4.2% nine months ago. • Inflation is stable...
Use the confusion matrixes to answer the questions below. Record your answers in a word document....
Use the confusion matrixes to answer the questions below. Record your answers in a word document. Explain your responses and include screen shots where requested. A 5000 row dataset was used to build a model to predict if a person would accept a marketing offer for a personal loan (Personal Loan = Yes). It was partitioned into Training, Validation, and Test with the model results above. If you were to decrease the cutoff to 0.3 how would that impact your...
Answer 2 of the following questions and relate your answer with other students’ answers: 1. If...
Answer 2 of the following questions and relate your answer with other students’ answers: 1. If your incomes increases by 20 percent, how much would your quantity demanded change per month on average? Estimate your income elasticity and explain your answer. 2. What is the cross-elasticity of supply of one of the goods or services that your company provides? Why? How does your answer relate with another student answer? 3. Gridlock in Toronto already costs the region $6 billion a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT