运行 带有 system() 的系统命令并发送输出

Run a system command with system() and send output

所以我想做的是用 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));

您应该只使用 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);