C++调用脚本的两种方式
1. system()
—执行shell命令也就是向dos发送一条指令,
system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。
#include <stdlib.h>
int system(const char * string);
- 函数说明
system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。 - 返回值
1、system()在调用/bin/sh时失败则返回127, 其他失败原因返回-1
2、若参数string 为空指针(NULL), 则返回非零值.
3、system()调用成功则最后会返回执行shell 命令后的返回值,但是此返回值也有可能为system()调用/bin/sh失败所返回的127,因此最好能再检查errno来确认执行成功 - 特点
1、根据返回值判断执行结果比较繁琐
2、无法去的shell脚本返回值
3、用system()来调用一个shell命令,或较短的shell脚本。较为方便
2. popen()
进程I/O函数,与pclose函数一起使用
#include <stdio.h>
FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream );
-
函数说明
1、popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。
2、这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。
3、如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样
-
返回值
调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流
-
特点
1、用 创建管道 的 方式 启动 一个 进程, 并调用 shell
2、可在程序内部获取shell执行后的返回内容
c++ 调用shell脚本并传递参数案例
#! /bin/bash
wget -P /shell/ $1 &>/dev/null
[ $? -eq 0 ] && echo "当前网站服务是ok" && rm -f /shell/index.* || echo "当前网站服务不ok,请立刻处理"
if [ -e upgrede.txt ]; then
echo "upgrede system!"
fi
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
int main()
{
char strone[]="/root/shellScript/upgradeProgram.sh";
char strtwo[]=" https://down.sandai.net/thunder11/XunLeiWebSetup11.3.10.1912gw.exe";
strcat(strone,strtwo);
system(strone);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)