首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

获取shell脚本的退出代码,在C程序中

可以使用system函数来执行shell脚本,并通过WEXITSTATUS宏来获取脚本的退出代码。

具体步骤如下:

  1. 在C程序中包含头文件#include <stdlib.h>#include <sys/wait.h>
  2. 使用system函数执行shell脚本,例如system("sh script.sh"),其中"script.sh"是你要执行的shell脚本。
  3. 使用waitpid函数等待子进程结束,并通过WEXITSTATUS宏获取子进程的退出代码。示例代码如下:
代码语言:c
复制
#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>

int main() {
    int status;
    if (system("sh script.sh") == -1) {
        // 执行shell脚本失败
        printf("执行shell脚本失败\n");
        exit(EXIT_FAILURE);
    }
    if (waitpid(-1, &status, 0) == -1) {
        // 等待子进程失败
        printf("等待子进程失败\n");
        exit(EXIT_FAILURE);
    }
    if (WIFEXITED(status)) {
        // 子进程正常退出
        int exit_code = WEXITSTATUS(status);
        printf("shell脚本的退出代码:%d\n", exit_code);
    } else {
        // 子进程异常退出
        printf("子进程异常退出\n");
    }
    return 0;
}

这样就可以在C程序中获取到shell脚本的退出代码了。

推荐的腾讯云相关产品:腾讯云服务器(CVM),产品介绍链接地址:https://cloud.tencent.com/product/cvm

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券