调用shell脚本的几种方式(c接口)

一、system调用shell脚本
首先,我们用的是shell脚本,即我们环境是linux下进行的,我这里用的是win11的ubuntu子系统,脚本如下:
test.sh

#! /bin/sh

echo "Hello world."

调用接口如下:

#include <stdlib.h>
int system(char *command)

这个函数是用来调用系统命令的,windows下是调用dos命令,linux下是调用shell命令。很多用vs做练习的同学应该都知道system(“pause”)这个用法,这里就是调用了pause命令使得结果输出窗口不会闪退。
代码如下:

#include <iostream>

int main() 
{
    
    
	system("./test.sh");
	return 0;
}

如果你把上面脚本扩展进了系统命令中,就不用指定路径,直接像使用系统命令一样调用该脚本。
输出结果如下:

jack@DESKTOP-SJO8SMG:/mnt/c/Users/samu$ g++ test.cpp -o test
jack@DESKTOP-SJO8SMG:/mnt/c/Users/samu$ ./test
Hello world.

二、使用popen创建管道来调用进程

#include <stdio.h>
FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream );

该函数通过调用fork函数来创建子进程,并在该进程调用shell命令,注意,使用popen创建的进程须由pclose关闭。
test.c

#include <stdio.h>
#include <string.h>

int main()
{
    
    

        FILE *fp;
        char buf[20];
        memset(buf, 0x00, sizeof(buf));

        fp = popen("./test.sh", "r");
        fgets(buf, sizeof(buf), fp);

        printf("%s\n", buf);
        pclose(fp);
        return 0;
}

输出结果同上,同样的程序,都是调用脚本,当我们需要作出改动时,不需要对程序进行更改,然后编译,只改动脚本即可,这个就是我认识到的一个脚本很便利的一点。

猜你喜欢

转载自blog.csdn.net/weixin_44948269/article/details/121588853