如何创建一个读取最后一个命令退出状态的程序?

时间:2014-07-31 20:41:22

标签: c linux shell exit-code

在Linux C中,如何阅读最后一个程序的退出状态。

例如:

true; echo $?

将显示0表示成功。但是我想用C程序替换它:

true; ./echo_exit_status

最后退出代码$的方式/位置是什么?可以用于C程序吗?

2 个答案:

答案 0 :(得分:2)

最后一个命令的退出状态是可以被后续执行的程序访问(没有疯狂可怕的hackery - 用调试器附加到父shell或者某些东西)。

您可以编写将此值导出到环境中的shell函数或帮助程序 - 但是没有可能不需要shell参与的解决方案。

答案 1 :(得分:-2)

你必须知道pid,否则它http://linux.die.net/man/2/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 be
          employed only if WIFEXITED returned true.

以下是

的示例
   #include <sys/wait.h>
   #include <stdlib.h>
   #include <unistd.h>
   #include <stdio.h>

   int
   main(int argc, char *argv[])
   {
       pid_t cpid, w;
       int status;

       cpid = fork();
       if (cpid == -1) {
           perror("fork");
           exit(EXIT_FAILURE);
       }

       if (cpid == 0) {            /* Code executed by child */
           printf("Child PID is %ld\n", (long) getpid());
           if (argc == 1)
               pause();                    /* Wait for signals */
           _exit(atoi(argv[1]));

       } else {                    /* Code executed by parent */
           do {
               w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
               if (w == -1) {
                   perror("waitpid");
                   exit(EXIT_FAILURE);
               }

               if (WIFEXITED(status)) {
                   printf("exited, status=%d\n", WEXITSTATUS(status)); //this line will return the exit status, whether it was 1 or 0
               } else if (WIFSIGNALED(status)) {
                   printf("killed by signal %d\n", WTERMSIG(status));
               } else if (WIFSTOPPED(status)) {
                   printf("stopped by signal %d\n", WSTOPSIG(status));
               } else if (WIFCONTINUED(status)) {
                   printf("continued\n");
               }
           } while (!WIFEXITED(status) && !WIFSIGNALED(status));
           exit(EXIT_SUCCESS);
       }
   }