0

Here below i have a simple code snippet of application which takes request from several clients and invokes mathematical operations through exec and waits for result from invoked processes to return those results to the respective clients through pipes

   case '+':
        fret=fork();
        if(fret==-1)
          perror(" error in forking at add\n");
        else if(fret==0)
        {//child
          sprintf(s_rp,"%d",p_op[0]);
          sprintf(s_wp,"%d",p_op[1]);
          argm[0]="add";
         if((ret=  execve(argm[0],argm,argp))== -1)
         {
          printf("exeve of add failed \n");
          exit(1);
         }
        }
        else
        {//parent
          write(p_op[1],&request,sizeof(request));
          if((ret=waitpid(fret,&x,0))==-1)
            perror("Error with wait at +\n");
          read(p_op[0],&result,sizeof(result));
          write(fd_res,&result,sizeof(result));

        }
        break;

Here i am facing a simple issue of parent being executing first fastly,which makes the waitpid() to fail,generally waitpid() waits for the child to exit but in my case the child is not even created when parent encounters waitpid() fails

My question is instead of using a sleep() (which has solved my problem but making the program run slow !! ) or any IPC How can i make sure the fork to execute my child first than my parent

when i thought of this, some approaches reeled in my mind, like making use of signals to block parent or semaphores to achieve atomicity is there any simple approach that makes sure my child will execute first and then my parent start execution

kakeh
  • 403
  • 3
  • 17

1 Answers1

1
  1. The waitpid function will BLOCK until the specified process ends. Although some other reasons such as EINTR can cause waitpid to return -1, it is very easy to solve that by placing the waitpid call into a loop. For example, if waitpid call returned -1 and errno == EINTR, then just continue the loop. See http://linux.die.net/man/3/waitpid about the return value.

  2. Your waitpid call will NEVER be executed before the child process is created! Obviously, the waitpid function is called after the fork syscall, and the return value of the fork syscall is not -1. So, at that time, the fork call has already returned which means that the child process would already exist.

nicky_zs
  • 3,633
  • 1
  • 18
  • 26
  • in concern to your 2nd statement : but my perror under waitpid reported 'no child processes on the console' why so – kakeh Jul 10 '14 at 17:09
  • 1
    Your case can't reappear in my ubuntu 12.04 x86_64 machine. Can you modify your code or post another code which can be compiled and executed by me? @Shyam – nicky_zs Jul 11 '14 at 02:02