c program fork and wait golang process status

huangapple go评论70阅读模式
英文:

c program fork and wait golang process status

问题

C程序:

pid = fork();

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

Golang程序:

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

但是,输出结果是:
进程 XXX 状态:256

如果设置 os.Exit(2),输出结果是:
进程 XXX 状态:512

如果设置 os.Exit(3),输出结果是:
进程 XXX 状态:768

为什么会这样呢?

这段代码中,父进程通过调用wait函数来等待子进程的结束,并获取子进程的退出状态。在Golang程序中,通过调用os.Exit来退出程序,并传递一个整数值作为退出状态码。在C程序中,通过wait函数获取到的退出状态码是子进程退出时传递给exit系统调用的值的两倍。因此,当Golang程序中使用os.Exit(1)时,C程序中获取到的退出状态码是256,os.Exit(2)时是512,os.Exit(3)时是768。这是因为C程序中的wait函数将子进程的退出状态码左移了一位。

英文:

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?

答案1

得分: 4

请参考wait手册

> 如果status不是NULL,wait()waitpid()会将状态信息存储在指向的整数中。可以使用以下宏来检查这个整数(这些宏将整数本身作为参数,而不是指向它的指针,与wait()waitpid()的做法不同!)

> WIFEXITED(status)如果子进程正常终止(通过调用exit(3)_exit(2),或从main()返回),则返回true

> WEXITSTATUS(status)返回子进程的退出状态。这包括子进程在调用exit(3)_exit(2)时指定的状态参数的最低有效8位,或在main()中作为返回语句的参数。只有当WIFEXITED返回true时,才应使用此宏。

你的问题与golang无关,你只需要使用这些宏来提取状态码:

if (WIFEXITED(status)) {
  printf("进程 %d 的状态: %d\n", pid, WEXITSTATUS(status));
}
英文:

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

huangapple
  • 本文由 发表于 2014年4月2日 16:02:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/22805059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定