system 函数原型
int system(const char *command);
函数说明
输入command指的是要执行的shell命令。
popen()/pclose()函数原型
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
函数原理
popen函数是首先fork一个子进程,然后exec,执行一个shell,在这个shell中执行参数command命令。参数type 可读r,可写w,不能同时。rw和r一样。使用完之后记得使用pclose关闭。
例子1:读取执行命令的返回值
void print_result(FILE *fp)
{
char buf[100];
if(!fp) {
return;
}
printf("\n>>>\n");
while(memset(buf, 0, sizeof(buf)), fgets(buf, sizeof(buf) - 1, fp) != 0 ) {
printf("%s", buf);
}
printf("\n<<<\n");
}
int main(void)
{
FILE *fp = NULL;
fp = NULL;
fp = popen("ntpdate time.pool.aliyun.com", "r"); //执行命令
if(!fp)
{
perror("popen");
exit(EXIT_FAILURE);
}
print_result(fp);
pclose(fp);
return 0;
}
例子2:system和popen()函数对比使用
#include <stdio.h>
#include <stdlib.h>
#define BUF_LEN 128
void cmd_exec(const char* cmd,char*result)
{
FILE *fp = NULL;
if(result == NULL)
return;
fp = popen(cmd,"r");
if(!fp)
{
perror("popen");
exit(EXIT_FAILURE);
}
while(fgets(result, BUF_LEN, fp) != 0 )
{
// printf("%s", result);
}
pclose(fp);
}
int main(void)
{
char buf[BUF_LEN] = {0};
int ret = 0;
ret = system("ntpdate time.pool.aliyun.com");
printf("ret = %d",ret);
cmd_exec("echo $?",buf);
printf("echo result %s",buf);
return 0;
}