Linux下C语言执行shell命令

有时候在代码中需要使用到shell命令的情况,下面就介绍一下怎么在C语言中调用shell命令:

这里使用popen来实现,关于popen的介绍,查看 http://man7.org/linux/man-pages/man3/popen.3.html

 #include <stdio.h>
#include <string.h>
#include <errno.h> static long get_used_space(const char *dir) {
long lUsedSpace = ;
char cmd[] = "";
char buf[] = "";
snprintf(cmd, , "du -sk %s | awk '{print $1}'", dir);
printf("%s\n", cmd);
FILE *pFile = popen(cmd, "r");
if (pFile == NULL) {
printf("popen() failed, error:%s\n", strerror(errno));
return lUsedSpace;
}
fgets(buf, sizeof(buf), pFile);
pclose(pFile);
lUsedSpace = atol(buf);
return lUsedSpace;
} int main()
{
long lUsedSpace = get_used_space("/var/log/");
printf("UsedSpace:%ld\n", lUsedSpace);
return ;
}

需要注意的是type参数,只能是读或写:

Linux下C语言执行shell命令

上一篇:《深入Java虚拟机学习笔记》- 第8章 连接模型


下一篇:Import data from SQLServer with Sqoop