i have tried both fork() and vfork() and get a float pt excep with fork and a seg fault with vfork. for no apparent reason when i use vfork() it exits the child but doesnt enter the parent and then seg faults. when i use fork() it enters the parent but gives me a float pt excep. any ideas?
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int sum = 0;
int i = 0;
pid_t pID;
int main()
{
pID = vfork();
if (pID > 0)
{
std::cout<< "b4 NULL"<< i<< "__"<< sum << std::endl;
wait(NULL);
std::cout<< "after NULL"<< i<< "__"<< sum << std::endl;
int avg = sum/i;
std::cout<<avg;
}
else if (pID == 0)
{
int J = 0;
std::cout<<sum<<"__"<<i<<std::endl;
i=0;
sum=0;
std::cout<<"enter a num:";
std::cin>>J;
while(J != -1)
{
sum += J;
std::cout<<"enter a num:";
std::cin>>J;
i++;
}
//int avg = sum/i;
//std::cout<<avg;
std::cout<<"exit child"<< i << "__" << sum << "__" << sum/i << std::endl;
//return(sum);
}
else
{
std::cerr << "Failed to fork" << std::endl;
return 1;
}
return 0;
}
You can't use
vfork
here.Your child modifies data, calls
operator<<
and all kinds of things that are not allowed. So that's not going to work.With
fork
, you divide by zero:No code changes
i
, andi
's value is zero. So you divide by zero here.