我正在尝试重新创建像 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);}
我是一名优秀的程序员,十分优秀!