C語言呼叫System命令並獲取命令的返回值

vc66vcc發表於2016-12-07


/* just get lastest info */
int _System(const char * cmd, char *pRetMsg, int msg_len)
{
	FILE * fp;
	char * p = NULL;
	int res = -1;
	if (cmd == NULL || pRetMsg == NULL || msg_len < 0)
	{
		printf("Param Error!\n");
		return -1;
	}
	if ((fp = popen(cmd, "r") ) == NULL)
	{
		printf("Popen Error!\n");
		return -2;
	}
	else
	{
		memset(pRetMsg, 0, msg_len);
		//get lastest result
		while(fgets(pRetMsg, msg_len, fp) != NULL)
		{
			printf("Msg:%s",pRetMsg); //print all info
		}

		if ( (res = pclose(fp)) == -1)
		{
			printf("close popenerror!\n");
			return -3;
		}
		pRetMsg[strlen(pRetMsg)-1] = '\0';
		return 0;
	}
}

int main()
{
	//test cmd
    char *cmd = "lsmod";
    char a8Result[128] = {0};
    int ret = 0;
    ret  = _System(cmd, a8Result, sizeof(a8Result));
    printf("ret = %d \na8Result = %s\nlength = %d \n", ret, a8Result, strlen(a8Result));
    return 0;
}

簡單的例項,C語言呼叫System命令,並且取得返回值(提供一個思路),程式碼僅僅返回的是最後一行的資訊。

如果獲取所有的內容,可以使用連結串列儲存每一行資料即可!


相關文章