—执行shell命令也就是向dos发送一条指令,
system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。
//相关函数:fork, execve, waitpid, popen #include//头文件 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脚本。较为方便
进程I/O函数,与pclose函数一起使用
#include//头文件 //函数定义 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执行后的返回内容
- test.sh
#! /bin/bash
# 判断门户网站是否能够正常提供服务
#定义变量
#web_server=https://down.sandai.net/thunder11/XunLeiWebSetup11.3.10.1912gw.exe
#访问默认网站
#wget -P /shell/ $web_server &>/dev/null
#访问参数传入网站
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
- main.c
#include#include #include #include int main() { char strone[]="/root/shellScript/upgradeProgram.sh";//脚本文件所在的完整路径 char strtwo[]=" https://down.sandai.net/thunder11/XunLeiWebSetup11.3.10.1912gw.exe"; //删除文件中包含dd内容的行 strcat(strone,strtwo); system(strone); return 0; }



