【问题标题】:exit(int) gives wrong value [duplicate]exit(int) 给出错误的值[重复]
【发布时间】:2021-07-03 19:20:20
【问题描述】:

我有一个多进程程序,它运行 4 个应该返回退出值的进程。
但是当进程到达 exit(int) 行时,它实际上将其他值返回给 wait()
例如: exit(1) 将给 wait() 值 256
退出(3) - 768
退出(4) - 1024
等等。我猜它会在 exit(int) 中返回一个值乘以 256。
为什么会发生这种情况以及如何解决(?)这个?

【问题讨论】:

  • 你使用的是什么操作系统?
  • 我不明白你为什么使用exit()
  • @ThomasMatthews 我正在使用 ubuntu。我需要退出来终止进程并接收终止代码
  • 您只能便携使用值EXIT_FAILUREEXIT_SUCCESS0 之一调用exit()

标签: c++ multiprocessing return


【解决方案1】:

您不能直接使用wait 提供的值,因为它以实现定义的方式对附加信息进行编码。如果进程退出,您必须使用WEXITSTATUS 宏和/或其他宏,如WTERMSIGWSTOPSIG,如果涉及信号。改编自man 2 wait

int wstatus;
w = wait(&wstatus);
if (w < 0) {
    perror("wait");
    exit(EXIT_FAILURE);
}

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

在我的系统(Ubuntu 通过 WSL)上,WEXITSTATUS 定义为:

#define __WEXITSTATUS(status)   (((status) & 0xff00) >> 8)
...
# define WEXITSTATUS(status)    __WEXITSTATUS (status)

这与您观察到的情况相符,其中获得的值是预期退出代码的 256 倍。但是,由于编码是由实现定义的,因此您不应该自己做出这种假设。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多