C语言中如何执行shell脚本并获取返回值

C语言中如何执行shell脚本并获取返回值,第1张

    在做开发过程中我们有时候会需要通过C语言来调用底层的shell脚本,并根据shell脚本的返回值来确认脚本是否正常的执行,本次就简单的梳理一下C语言调用shell脚本的方式。


 

方式特点
system简单,但是无法获取命令执行(输出)结果,只能获取返回值
popen业务开发中大部分都是使用这种方式,较为推荐
exec函数组使用较少

综上,如果只是获取命令执行是否成功那就用第一种system,而如果需要获取执行命令时的输出,那么可以使用popen方式,最后一个exec,这个可以看情况使用,一般情况下不推荐

使用system函数

    这种方式是最为简单的,在程序中只需要引入相关lib库即可

#include 
#include 

int main(){
    char* cmd="sh test.sh";
    int ret = system(cmd);
    if(ret!=0){
        printf("execute result is %d",ret);
    }
}

shell脚本内容如下

#!/bin/bash

echo "hello world"

执行完成后控制台输出

hello world
execute success
使用popen方式

    使用popen代码如下

#include 
#include 

int main(){
    FILE * fp;
    char buffer[80];
    fp=popen("./test","r");
    fgets(buffer,sizeof(buffer),fp);
    printf("%s",buffer);
    pclose(fp);
}
exec函数组

这种方式也是查网上资料获取的,具体如下

#include 
#include 
#include
#include

int main()
{
    int childpid=0;
    if ((childpid=fork()) == 0)
    {
        // child
        char *execv_str[] = {"sh", "test.sh", NULL};
        if (execv("/bin/sh", execv_str) < 0)
        {
            perror("exec error\n");
            exit(0);
        }
    }
    else
    {
        // parent
        wait(&childpid);
        printf("execv finshed\n");
    }
}

执行结果为

hello world
execute finshed

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/578343.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-11
下一篇 2022-04-11

发表评论

登录后才能评论

评论列表(0条)

保存