c程序分叉并等待golang进程状态 [英] c program fork and wait golang process status

查看:143
本文介绍了c程序分叉并等待golang进程状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C程序:

  pid = fork(); 

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

Golang计划:

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

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



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

如果设置os.Exit(3),输出是:
process XXX status:768



为什么?

解决方案

a href =http://linux.die.net/man/2/wait =nofollow noreferrer> wait manual :


如果状态不是NULL, wait() waitpid )在它指向的int中存储状态信息
可以使用
跟随宏(它将整数本身作为参数,而不是
指针指向它)来检查此整数,如 wait() waitpid()!)


WIFEXITED(status)返回 true 如果孩子正常终止,即
,通过调用 exit( 3) _exit(2),或者从 main()返回



WEXITSTATUS(status)返回孩子的退出状态。这个
由状态变量的最低有效8位组成,
是在调用 exit(3)或<$ c $时指定的子元素c> _exit(2)或者作为 main()中返回语句的
参数。如果 WIFEXITED 返回 true


您的问题与golang无关,您只需使用这些宏提取状态代码即可:



<$ p $ (WIFEXITED(status)){
printf(process%d status:%d \ n,pid,WEXITSTATUS(status));
}


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

这篇关于c程序分叉并等待golang进程状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆