一、system函数
1、system函数功能
system函数其实就是exec族函数的封装,完成exec族函数某一进程中执行可执行性程序的功能,但与exec族函数不同的是,exec族函数在执行完某一程序不会再返回该进程,执行exec族函数语句后面的代码,而system函数在执行完某一可执行性程序还会返回该进程,执行其后面的语句。
system函数相比exec族函数,更简单容易深受程序员的喜爱。
2、demo验证
#include <stdio.h>
#include <stdlib.h>//system头文件
//函数原型:int system(const char *command);
int main()
{
printf("before system\n");
char *cmd = "date";
if(system(cmd)==-1)
{
printf("system failed\n");
perror("why");
}
printf("after system\n");
return 0;
}
执行结果:
before system
Thu Jul 2 20:28:00 CST 2020
after system
3、system函数返回值说明
成功则返回进程的状态值,当sh不能执行时,返回127,否则返回-1。
sh命令是终端命令语言解释器,通过用户输入命令和内核进行沟通。
二、popen函数
1、popen函数的功能
system函数将执行指令的结果直接输出到终端
而popen函数可以获取指令运行的输出结果,存放于文件流中,并不会直接输出到终端
2、popen函数说明
#include <stdio.h>
函数原型:FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen函数参数一:是一个字符串指针,其中存放执行的指令
popen函数参数二:是一个字符串指针,其必须是r或者w,用来指明读还是写
popen函数返回值:返回一个文件流指针,只能用pclose函数来关闭,向这个流的写入被转化为对 command命令的标准输入,可以用fread函数读取流中的标准输出
3、popen函数demo验证
#include<stdio.h>
int main()
{
FILE *fp;
char readBuf[128];
fp = popen("date","r");
if(fp ==NULL)
{
printf("popen failed\n");
}
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
int n_read = fread(readBuf,1,128,fp);
printf("read size is %d,context is %s\n",n_read,readBuf);
pclose(fp);
return 0;
}
执行结果
read size is 29,context is Thu Jul 2 21:12:14 CST 2020