Question

1. Write program codes for 3.21 a and shared memory program b for producer and consumer as shown in the following. You can st

n= integer is passed on the command line. Programming Problems 155 3.21 The Collatz conjecture concerns what happens when we

Source code to modify:

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

int main()

{

pid_t pid;

/*fork a child process*/

pid = fork();

if (pid<0){ /*error occured*/

fprintf(stderr,"Fork failed\n");

return 1;

}

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

printf("I am the child %d\n",pid);

execlp("/bin/ls","ls",NULL);

}

else { /*parent process */

/*parent will wait for the child to complete*/

printf("I am the parent %d\n",pid);

wait(NULL);

printf("Child Complete\n");

}

return 0;

}

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

//Working Code :-

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int n=35;
int main(){
pid_t pid;
pid = fork();
if (pid<0){ 
fprintf(stderr,"Fork failed\n");
return 1;
}
else if (pid == 0) { 
    execv("child",NULL);
printf("Now executing child \n ");
while(1){
    printf("%d ",n);
    if(n==1)
    break;
    else
    {
        if(n%2==0)
        n=n/2;
        else
        n = (3*n)+1;
    }
}
printf("\n");
exit(1);
}
else { 
printf("first execution by parent class \n");
wait();
printf("Child Complete\n");}
return 0;
}


//Output ;-

/tmp/6KSqV79rez.o first execution by parent class Now executing child 35 106 53 160 80 40 20 10 5 16 8 4 2 1 Child Complete #

//Comments :- keep parent process in wait() state till child process get complete , child process notifies with exit(1) code that it is done then parent process will continue , and also in above code while(1) is written , insense think contrary to above collatz conjecture, if its false then it the code should run infinite times , but when you run you will see it runs for definite time and stope when n value is 1, for simplicity n is predeclared as global variable can change if one wants to

Add a comment
Know the answer?
Add Answer to:
Source code to modify: #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { pid_t pid; /*fork...
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