1、system()
#include <stdlib.h>
int system(const char *str)
编写脚本test.sh:
#!/bin/sh
echo $HOME
编写代码:
#include <stdlib.h>
#include <iostream>
#include <string>
int main()
{
std::string res;
res = system("./test.sh");
std::cout << res << '\n';
return 0;
}
特点:
1.两种错误返回值:
-1 system()进行fork子进程失败;
127 执行脚本或shell命令失败
2.无法在程序中直接获取到shell命令的返回内容
2、popen()
标准I/O函数库提供了popen函数,它启动另外一个进程去执行一个shell命令行。
这里我们称调用popen的进程为父进程,由popen启动的进程称为子进程。
popen函数还创建一个管道用于父子进程间通信。父进程要么从管道读信息,要么向管道写信息,至于是读还是写取决于父进程调用popen时传递的参数。下在给出popen、pclose的定义:
01 #include <stdio.h>
02 /*
03 函数功能:popen()会调用fork()产生子进程,然后从子进程中调用/bin/sh -c来执行参数command的指令。
04 参数type可使用“r”代表读取,“w”代表写入。
05 依照此type值,popen()会建立管道连到子进程的标准输出设备或标准输入设备,然后返回一个文件指针。
06 随后进程便可利用此文件指针来读取子进程的输出设备或是写入到子进程的标准输入设备中
07 返回值:若成功则返回文件指针,否则返回NULL,错误原因存于errno中
08 */
09 FILE * popen( const char * command,const char * type);
10
11 /*
12 函数功能:pclose()用来关闭由popen所建立的管道及文件指针。参数stream为先前由popen()所返回的文件指针
13 返回值:若成功返回shell的终止状态(也即子进程的终止状态),若出错返回-1,错误原因存于errno中
14 */
15 int pclose(FILE * stream);
编写代码:
#include <stdio.h> //popen()
#include <string.h> //memset()
int main()
{
FILE *fp;
char buffer[80];
memset(buffer, 0x00, sizeof(buffer));
fp = popen("./test.sh", "r");
fgets(buffer, sizeof(buffer), fp);
printf("[%s]\n", buffer);
pclose(fp);
return 0;
}
特点:
1. 用 创建管道 的 方式 启动 一个 进程, 并调用 shell
2. 可在程序内部获取shell执行后的返回内容