c - $status 在 C shell 中指的是什么?

标签 c shell csh

我正在尝试重新创建像 tcsh 这样的基本 C Shell,但我正在理解变量 $status。这是 tcsh 中的状态示例:

存在的命令:

$> pwd
/home/user
$> echo $status
0

一个不存在的命令:

$> foo
foo: Command not found.
$> echo $status
1

status 的值指的是什么?从 tcsh 返回值?

最佳答案

$status$? 表示之前启动命令的退出状态。更准确地说,是子进程的退出状态。因为在命令不存在的情况下,有一个 fork 的子 shell,但它无法exec() 命令。

Shell 通常会像这样启动一个命令:

int pid = fork();
if (pid == 0) {   /* Child shell process */
    /* Try to replace child shell with cmd, in same child PID */
    /* cmd will generate the exit status of child process */
    execve(cmd, argv, envp);

    /* If execve returns, it's always an error */
    /* Child shell generates exit status for error */
    write(2, "command not found\n", 18);
    exit(127);
} else {          /* Parent shell process */
    /* Original shell waits for child to exit */
    int status;
    wait(&status); /* Assuming only one child */

    /* this is accessible in shell as $status or $? */
    status = WEXITSTATUS(status);
}

关于c - $status 在 C shell 中指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41704249/

相关文章:

linux - 如何使用来自另一个文件的参数列表运行 Makefile

c - Eclipse:用 C 创建 Hello World 应用程序

c++ - 为什么 semop() 挂起?

c - 使用C中的函数将二维数组写入文件

Python运行shell命令并模拟用户输入

c - 如何用C语言打开一个处于读写执行模式的文件(shell编程)

c - 用C语言初始化LCD显示屏PIC16F1829?

bash - 创建在当前目录中运行 python 脚本的 Shell 脚本

shell - 如何每小时运行 "at"命令

linux - 在 `alias` 中加上引号就是 `CSH`