有時候在代碼中須要使用到shell命令的狀況,下面就介紹一下怎麼在C語言中調用shell命令:html
這裏使用popen來實現,關於popen的介紹,查看 http://man7.org/linux/man-pages/man3/popen.3.htmllinux
1 #include <stdio.h> 2 #include <string.h> 3 #include <errno.h> 4 5 static long get_used_space(const char *dir) { 6 long lUsedSpace = 0; 7 char cmd[1024] = ""; 8 char buf[1024] = ""; 9 snprintf(cmd, 1024, "du -sk %s | awk '{print $1}'", dir); 10 printf("%s\n", cmd); 11 FILE *pFile = popen(cmd, "r"); 12 if (pFile == NULL) { 13 printf("popen() failed, error:%s\n", strerror(errno)); 14 return lUsedSpace; 15 } 16 fgets(buf, sizeof(buf), pFile); 17 pclose(pFile); 18 lUsedSpace = atol(buf); 19 return lUsedSpace; 20 } 21 22 int main() 23 { 24 long lUsedSpace = get_used_space("/var/log/"); 25 printf("UsedSpace:%ld\n", lUsedSpace); 26 return 0; 27 }
須要注意的是type參數,只能是讀或寫:shell