Reputation: 573
I have to create a program that:
Here is my code
#include <stdio.h>
#include <sys/types.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
double n=0;
printf("Number: "); //ask number
scanf("%d", &n);
pid_t pid = vfork(); //create child process
if (pid==0)//if child process
{
printf("Child process started\n");
n = sqrt(n);//calculate square root
}
else//parent process
{
printf("Returnning to parent process\n");
printf("Square Root: %d",n);
}
return 0;
}
But my code doesnt work, can anyone help me?
Upvotes: 0
Views: 861
Reputation: 19
int main(int argc, char **argv) { int n=0;
pid_t pid = vfork(); //create child process
if (pid==0)//if child process
{
printf("Child process started\n");
scanf("%d",&n);
n = sqrt(n);//calculate square root
_exit(23);
}
else//parent process
{
printf("Returnning to parent process\n");
printf("Square Root: %ld",n);
}
return 0; }
Upvotes: 0
Reputation: 215287
Why would you expect it to work? Doing anything but exec
or _exit
after vfork
results in explicitly undefined behavior. See:
And some further discussion of the horrors of vfork
:
http://www.openwall.com/lists/musl/2012/12/31/16
In case it's interesting, here is a list of possible problems with your program (manifestations of the UB):
printf
in the child could horribly corrupt the parent's stdio state.n
could be stored permanently in a register, in which case there's no way the parent could see the changes made by the childn
is uninitialized in the else
branch, so it need not generate any code to read it at all (this branch unconditionally invoked UB by accessing an object whose value is indeterminate).Upvotes: 2
Reputation: 125007
You're calculating the square root in the child, but trying to print it in the parent. The parent has no idea what the square root is. If you want the parent to print the square root, then you'll need to communicate that value from the child back to the parent process somehow. It seems more likely that you're supposed to print the square root in the child process.
Upvotes: 0