在做开发过程中我们有时候会需要通过C语言来调用底层的shell脚本,并根据shell脚本的返回值来确认脚本是否正常的执行,本次就简单的梳理一下C语言调用shell脚本的方式。
| 方式 | 特点 | 
|---|---|
| system | 简单,但是无法获取命令执行(输出)结果,只能获取返回值 | 
| popen | 业务开发中大部分都是使用这种方式,较为推荐 | 
| exec函数组 | 使用较少 | 
综上,如果只是获取命令执行是否成功那就用第一种system,而如果需要获取执行命令时的输出,那么可以使用popen方式,最后一个exec,这个可以看情况使用,一般情况下不推荐
使用system函数
这种方式是最为简单的,在程序中只需要引入相关lib库即可
#include <stdlib.h>
#include <stdio.h>
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 <stdlib.h>
#include <stdio.h>
int main(){
    FILE * fp;
    char buffer[80];
    fp=popen("./test","r");
    fgets(buffer,sizeof(buffer),fp);
    printf("%s",buffer);
    pclose(fp);
}
 
exec函数组
这种方式也是查网上资料获取的,具体如下
#include <stdlib.h>
#include <stdio.h>
#include<unistd.h>
#include<sys/wait.h>
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










