0
votes

I have passed an argument in exit code of a child process, So in the parent process I am trying the call another function that passes the exit status code passed by the child process by using wait, However I am only getting -1 as the exit status code on using the wait call, is there any way to get the parameter passes in the exit code on calling the wait method.

#include <stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include<sys/wait.h>

pid_t ppid;

void child();
void parent();


int get_child_exit_status()
{
    int status=wait(&ppid);

    return status; //returns -1 instead of 101
      
}
int main(void)
{  
         
   ppid = getpid();
  
    fork();
    child();
    wait(&ppid);
    printf("Child exited with status=%d",get_child_exit_status());
    return 0;

}


void child()
{
        pid_t c_pid = getpid();
        if(c_pid == ppid)
        {
          
                return;
            
        }

        printf("This is a child\n");
        int status;
    
        scanf("%d",&status); //input 101

        exit(status);
}
1
See man 3 wait. There's an example there... - KamilCuk

1 Answers

0
votes

Your code is confusing. Try to make it simple:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    int status;
    int code;

    switch (fork()) {
    case 0: // child code
        scanf("%d", &code);
        return code;
    default: // parent code
        wait(&status);
        printf("child exited with status %d\n", WEXITSTATUS(status));
        return 0;
    }
}

I used switch here so you can easily add a case for -1 to deal with any errors when forking.