Domanda

As far as I know if waitpid returns -1 then it is error condition. How it possible to get success (EXIT_SUCCUSS) from child process in WEXITSTATUS(childStatus)?

What is the difference between childStatus in waitpid & return value from WEXITSTATUS(childStatus)? Does it same?

pid_t returnValue = waitpid(Checksum_pid, &childStatus, WNOHANG);
printf("return value = %d", returnValue);
printf("return value = %d", childStatus);

if (WIFEXITED(childStatus))
        {
            printf("Exit Code: _ WEXITSTATUS(childStatus)") ;    
            //Proceed with other calculation.  
        }
È stato utile?

Soluzione

When using the option WNOHANG, I would expect that most of the time waitpid will return -1, with errno set to ECHILD.

In any case, whenever waitpid does return -1, you shouldn't be looking at childStatus, which (for all I know) could be just garbage. Instead, look at errno, and handle it appropriately.

Otherwise, your code seems to be ok, as far as it goes, and you should be able to extract a 0 or EXIT_SUCCESS from childStatus.

The man page for waitpid suggests the following sample code:

   if (WIFEXITED(status)) {
       printf("exited, status=%d\n", WEXITSTATUS(status));
   } else if (WIFSIGNALED(status)) {
       printf("killed by signal %d\n", WTERMSIG(status));
   } else if (WIFSTOPPED(status)) {
       printf("stopped by signal %d\n", WSTOPSIG(status));
   } else if (WIFCONTINUED(status)) {
       printf("continued\n");
   }

although it might be a good idea to add a final else printf("oops?\n") statement to this.

Altri suggerimenti

WIFEXITED will read whatever value is stored in childStatus, which is just an integer, so it doesn't have to come from waitpid() - try eg

for(i = 0; i < 1234; i++)
        printf("WIFEXITED(%d) %s\n", i, WIFEXITED(i) ? "yes" : "no");

The difference between childSTatus and WIFEXITED(childStatus) is a bit tricky... Basically the exit status has been abused to tell the exit status or the signal that killed the process: you'd want something like

struct exitstatus {
        int status;
        int signalnumber;
        enum { exited, signaled };
};

but those informations have been squeezed into a single integer in some way (I'm not sure if the exact details are defined anywhere): eg on my computer the low 8 bits are used for the signal number (if any) and the bits 8-15 are used for the exit code. The important point anywhere is that you don't need to know how it happens, only how to get the results you want via WIFEXITED & friends.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top