一般我们调用shell脚本都用system()来实现,然后发现sytem返回值不好控制而且转换麻烦(还要右移4位即/256),于是我用popen来获取shell的返回值。果然在Unix世界里面,通道就是连结各个方面的桥梁啊!
代码例子如下:
#include
#include
#include
int main (int argc, char *argv[])
{
char szline[256];
FILE *fp;
if (argc != 2)
{
printf ("usage: %s command/n", argv[0]);
return 0;
}
if ((fp = popen (argv[1], "r")) == NULL)
{
printf ("the command %s not exist/n", argv[1]);
return 0;
}
while (fgets (szline, sizeof (szline) - 1, fp) != NULL)
{
printf ("frome command:%s", szline);
}
pclose (fp);
return 0;
}
PS:奇怪的是我用如下函数:
char* get_cmd_result(char* cmd)
{
FILE *fp;
char result[256];
memset (result, 0,sizeof(result));
if((fp=popen(cmd,"r"))==NULL)
{
printf("the command %s not exist/n",cmd);
pclose(fp);
return 0;
}
while(fgets(result,sizeof(result)-1,fp)!=NULL)
{
#ifdef __DEBUG__
g_print("get result is %s/n", result);
#endif
}
pclose(fp);
return result;
}
在debian sid下就没问题,在Ubuntu10.04上调用该函数就没法返回的正确值,但在g该函数里result是正确的,这个就不是该文讨论的问题了。