2016-09-30 122 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); 
相关问题