Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value from child process c

I need help returning a "status code" from my child program back to the parent, where it will check the status code, print code, and exit the parent. This is for a class project, so I will put some relevant code here, but I don't to post the entire project for obvious reasons.

I have forked and created the child process through exec. The parent does some fancy math and uses a named pipe to push data to the child process. The child does some more fancy math. When I uses a keyword, the child needs to return the number of times it did the fancy math on its end back to the parent, where the parent will see this, print out the returned number, and exit the parent.

    int status;
    pid_t child_id;
    child_id = fork();
    if (child_id == 0)
    {
            // put child code here
            exec(opens second process);
    }
     if (child_id < 0)
    {
            perror("fork failed\n");
            exit(EXIT_FAILURE);
    }

     while(child_id != 0)
     {
       //parent process
       //do fancy math stuff here
       // pipe
      //open pipe
      //converted math to "string" to pass to other program
      // use fprintf to send data to other program
      fprintf(fp,"%s",str);
      //close pipe
//**************************************************
//this block doesn't work, always returns 0
      if (WIFEXITED(status)){
            int returned = WEXITSTATUS(status);
            printf("exited normally with status %d\n",returned);
      }
//***************************************************
   return 0;

second c program is just a simple reading of the pipe, does some more fancy math, and has return statements placed where I want to return a number.

As far as I understand it, there is a way to pass the return value from the child program, but I can't seem to understand how. I haved added a piece of code that I found, but I can't seem to get it to work. I have read about it, but maybe I am missing something?

please disregard any syntax or structure issues.

like image 216
user7904063 Avatar asked Apr 22 '17 03:04

user7904063


1 Answers

You're attempting to read status via the WIFEXITED function, but you never give it a value. Attempting to read an uninitialized value invokes undefined behavior.

You need to call the wait function, which tells the parent to wait for a child to finish and receive its return code:

wait(&status);
if (WIFEXITED(status)){
      int returned = WEXITSTATUS(status);
      printf("exited normally with status %d\n",returned);
}
like image 190
dbush Avatar answered Sep 21 '22 10:09

dbush