سؤال

C program:

pid = fork();

if (pid == 0) {
    execv("Golang Process");
} else (pid > 0) {
    wait(&status);
    printf("process %d status: %d\n", pid);
}

Golang Program:

func main() {
    ......
    os.Exit(1)
}

But, output is: process XXX status: 256

if set os.Exit(2), output is: process XXX status: 512

if set os.Exit(3), output is: process XXX status: 768

Why?

هل كانت مفيدة؟

المحلول

See wait manual:

If status is not NULL, wait() and waitpid() store status information in the int to which it points. This integer can be inspected with the following macros (which take the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!):

WIFEXITED(status) returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().

WEXITSTATUS(status) returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.

Your issue is unrelated to golang, you just have to use these macros to extract the status code:

if (WIFEXITED(status)) {
  printf("process %d status: %d\n", pid, WEXITSTATUS(status));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top