return value from child process c
Asked Answered
A

1

6

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.

Abscission answered 22/4, 2017 at 3:41 Comment(1)
after the call to exec() insert the following two lines: perror( "exec failed" )l exit( EXIT_FAILURE ); for the 'rare' case when the call to exec() failedJaquenette
T
9

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);
}
Tamishatamma answered 22/4, 2017 at 3:48 Comment(1)
@Abscission Glad I could help. Feel free to accept this answer if you found it useful.Tamishatamma

© 2022 - 2024 — McMap. All rights reserved.