return value from child process c

谁说我不能喝 提交于 2019-12-21 18:41:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/43554978/return-value-from-child-process-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!