Hi everybody!

I am trying to use fork() and wait to perform a simple task with c++ but I have noticed that the performance is quite different from what I expected.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
  
{
  int number = atoi(argv[1]);
  int i;
  int pid;
  
  pid=fork();
  
  if (pid!=0){
    
    wait();
    printf ("hi!");  
  }
  
  else {
    sleep (3);	
    int i;
    
    printf("I am the child\n");
    
    printf("my pid=%d\n", getpid());
    
    printf("and my parent pid=%d\n", getppid());
      
  }
  
}

This code should create a child process and the parent waits for the child to end to print "hi!".

If I compile this code with gcc "gcc -o fork2 fork2.c" the code works as expected, whereas if I use g++ "g++ -o fork2 fork2.c" the output is different and the parent doesn't wait the child to end to print his message!

I need this to work in a bigger c++ program.

I am using RHEL with 2.6.18-194 kernel

Any advice will be greatly apreciated!

Thanks in advance!

Hi,

I think its not because of the different compiler, its because may be synchronization of parent and child is not happening properly, wait is getting executed even before child process starting.. or something like that?

anyway,

try this code and see what happened:

pid = fork();

switch(pid){
  case -1:
           perror("Fork failed");
           exit(1);
  case 0:
          //this is child;
         break;
  default:
       //parent
       break;
}

if(pid != 0)
{
   int stat_val;
   pid_t child_pid;
  
   child_pid = wait(&stat_val);
   
  if(WIFEXISTED)
     printf("Child has terminated with exit code %d\n",  WIFEXISTED(stat_val));
  else
     printf("Child has existed abnormally\n");
}


// Do some child code here..

miss typed:

if(WIFEXISTED)
will be
if( WIFEXISTED(stat_val) )

Working perfectly right now!

The code is as follows

#include <iostream>
#include <sys/wait.h>

using namespace std;

int main()
{
  pid_t pid = fork();

  switch(pid){
  case -1:
    perror("Fork failed");
    exit(1);
  case 0:
    sleep(10);
    cout << "Son code" << endl;
    //this is child;
    break;
  default:
    //parent
    break;
  }
  
  if(pid != 0) {
    int stat_val;
    pid_t child_pid;
    
    child_pid = wait(&stat_val);
    
    if(WIFEXITED(stat_val))
      printf("Child has terminated with exit code %d\n",  WIFEXITED(stat_val));
    else
      printf("Child has existed abnormally\n");
  }
  
  cout << "This one you will see in both programs!! It should be printed twice. Bye!" << endl;
  
  return 0; 
}

Sorry for the late reply!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.