2016-09-30 86 views
1

所以我想要做的是調用一個系統命令與system()函數,然後無論它的輸出是我想要它並將其發送到客戶端(套接字連接)。使用system()運行系統命令併發送輸出

客戶端可以發送各種消息。它可以是ls,但它可能是qwerty。我想輸出並將其作爲const void* buffer參數放入write()函數中。我看過this topic,但我可以完成它的工作。到目前爲止,我認爲它可以在這些線路的某個地方,但無論我嘗試它沒有奏效。

/* buffer is message from the client: ls, ls -l, whatever*/ 
system(buffer) 
fp = popen(buffer, "r"); 
if(fp == NULL) 
    printf("Failed ot run command\n"); 

while(fgets(path, sizeof(path), fp) != NULL) { 
    //modify output here? 
} 
pclose(fp); 
write(socket_fd, output, strlen(buffer)); 
+0

你在哪裏調用'系統()'? –

+0

@ Code-Apprentice右上方 – Lisek

+0

似乎命令行中的命令似乎也不是文件名。 –

回答

2

,才應使用popen()而不是system(),因爲它在你鏈接的問題描述。

您鏈接的問題中的path變量似乎被錯誤命名。它包含系統調用的輸出。如果您願意,您可以將其重新命名爲輸出。

write()取得您發送緩衝區的長度。在這種情況下,這將是output的長度,而不是buffer的長度。

把所有這些組合起來提供了以下:

char output[1035]; 
fp = popen(buffer, "r"); 
if(fp == NULL) 
    printf("Failed ot run command\n"); 

while(fgets(output, sizeof(output), fp) != NULL) { 
    write(socket_fd, output, strlen(output)); 
} 
pclose(fp);