this is my c code. i created 2 child processes. but i do not know how to solve b
ID: 3861382 • Letter: T
Question
this is my c code.
i created 2 child processes.
but i do not know how to solve below requirements...
can you add some codes for me? thanks
1. Make any of the variables of a parent share with any of its child processes
2. Make the children of the same parent share some variables between themselves
int main()
{
int fd;
pid_t pid;
pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error");
exit(EXIT_FAILURE);
}
//child 1
else if (pid == 0)
{
printf("I am child 1. ");
}
else
{
pid = fork();
// child 2
if (pid == 0)
{
printf("I am child 2. ");
}
else
{
wait (NULL);
exit(EXIT_SUCCESS);
}
}
}
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
int main()
{
int fd;
pid_t pid;
int share = 0;
pid = fork();
// from here onwards if fork is successfull ..system make two identical copies of address spaces
//both processes (parent and child) will start executing after fork() statement..
//they now share the same varaible,share
if (pid < 0)
{
fprintf(stderr, "Error");
exit(EXIT_FAILURE);
}
//child 1
else if (pid == 0)
{
printf("I am child 1. ");
share++;
printf("pid : %d ,share :%d ",getpid(),share);//shows which process is printing it..
//we can't expect a particular order here...
//both access printf buffer at same time//
}
else
{
pid = fork();
// child 2
//here child 2 ,child 1 and parent also sharing the same variable..
//because another identical address space is created for parent again..
if (pid == 0)
{
printf("I am child 2. ");
printf("pid : %d ,share :%d ",getpid(),share);//shows which process is printing it..
//we can't expect a particular order here...
//both access printf buffer at same time//
}
else
{
wait (NULL);
exit(EXIT_SUCCESS);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.