Linux下使用popen执行子进程并获得其输出

GString* exec_and_out(char* cmd)
{
GString* ret = g_string_new("");
FILE* stream = NULL;
char buf[128];
size_t len = 0;

//popen execute and open stream
stream = popen(cmd, "r");
if (stream != NULL)
{
while (!feof(stream))
{
len = fread(buf, sizeof(char), sizeof(buf), stream);
g_string_append_len(ret, buf, len);
}
}
//Clear the resource
if (stream != NULL)
{
pclose(stream);
}

return ret;
}

Leave a Reply

Your email address will not be published. Required fields are marked *