Linux 中是否有任何标准的退出状态代码?

新手上路,请多包涵

如果进程的退出状态为 0,则认为进程在 Linux 中已正确完成。

我已经看到分段错误通常会导致退出状态为 11,尽管我不知道这只是我工作的惯例(像这样失败的应用程序都是内部的)还是标准。

Linux 中的进程是否有标准的退出代码?

原文由 Nathan Fellman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 559
2 个回答

wait(2) & co. 返回时 8 位返回码和 8 位终止信号编号混合为一个值。 .

 #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>

int main() {
    int status;

    pid_t child = fork();
    if (child <= 0)
        exit(42);
    waitpid(child, &status, 0);
    if (WIFEXITED(status))
        printf("first child exited with %u\n", WEXITSTATUS(status));
    /* prints: "first child exited with 42" */

    child = fork();
    if (child <= 0)
        kill(getpid(), SIGSEGV);
    waitpid(child, &status, 0);
    if (WIFSIGNALED(status))
        printf("second child died with %u\n", WTERMSIG(status));
    /* prints: "second child died with 11" */
}

您如何确定退出状态?传统上,shell 只存储 8 位返回码,但如果进程异常终止,则设置高位。

$ sh -c '退出 42';回声$?
42
$ sh -c '杀死-SEGV $$';回声$?
分段故障
139
$ expr 139 - 128
11

如果您看到除此之外的任何内容,则程序可能有一个 SIGSEGV 信号处理程序,然后通常调用 exit ,因此它实际上并没有被信号杀死。 (程序可以选择处理除 SIGKILLSIGSTOP 之外的任何信号。)

原文由 ephemient 发布,翻译遵循 CC BY-SA 3.0 许可协议

第 1 部分:高级 Bash 脚本指南

与往常一样, Advanced Bash Scripting Guide 提供 了大量信息:(这在另一个答案中链接,但链接到非规范 URL。)

1: 捕获一般错误

2: 滥用 shell 内置函数(根据 Bash 文档)

126: 调用的命令无法执行

127: “找不到命令”

128: 退出参数无效

128+n: 致命错误信号“n”

255: 退出状态超出范围(退出只需要 0 - 255 范围内的整数 args)

第 2 部分:sysexits.h

ABSG 引用 sysexits.h

在 Linux 上:

 $ find /usr -name sysexits.h
/usr/include/sysexits.h
$ cat /usr/include/sysexits.h

/*
 * Copyright (c) 1987, 1993
 *  The Regents of the University of California.  All rights reserved.

 (A whole bunch of text left out.)

#define EX_OK           0       /* successful termination */
#define EX__BASE        64      /* base value for error messages */
#define EX_USAGE        64      /* command line usage error */
#define EX_DATAERR      65      /* data format error */
#define EX_NOINPUT      66      /* cannot open input */
#define EX_NOUSER       67      /* addressee unknown */
#define EX_NOHOST       68      /* host name unknown */
#define EX_UNAVAILABLE  69      /* service unavailable */
#define EX_SOFTWARE     70      /* internal software error */
#define EX_OSERR        71      /* system error (e.g., can't fork) */
#define EX_OSFILE       72      /* critical OS file missing */
#define EX_CANTCREAT    73      /* can't create (user) output file */
#define EX_IOERR        74      /* input/output error */
#define EX_TEMPFAIL     75      /* temp failure; user is invited to retry */
#define EX_PROTOCOL     76      /* remote error in protocol */
#define EX_NOPERM       77      /* permission denied */
#define EX_CONFIG       78      /* configuration error */

#define EX__MAX 78      /* maximum listed value */

原文由 Schof 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题