basic fork() program returns either seg fault or floating pt exception

504 Views Asked by At

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;
    }
2

There are 2 best solutions below

4
On

You can't use vfork here.

"... the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions." -- vfork

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:

int i = 0;
pid_t pID;

int main()
{   
     pID = fork(); /* changed to fork */
     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; /* division by zero */

No code changes i, and i's value is zero. So you divide by zero here.

4
On

You are dividing by zero within parent code:

int avg = sum/i;

The block if (pID == 0) is for the child, and when you fork, the child process is created as a clone of the original running process but in separate address space, the variable sum is not shared, rather have separate copies in child and parent, no sharing. For sharing, you need to us shared memory or pipe, To use global data in same address space, you need to create / use threads and not processes.