简体   繁体   English

将stdout和stderr重定向到套接字以获取分布式shell程序

[英]Redirect stdout and stderr to socket for a distributed shell program

I made a distributed shell program that has a client and server. 我制作了一个分布式shell程序,它有一个客户端和服务器。 The client sends a command request to the server and the server executes that command locally and is supposed to output the results of that command to the client. 客户端向服务器发送命令请求,服务器在本地执行该命令,并且应该将该命令的结果输出到客户端。 I am having trouble figuring out how to redirect stdout/stderr to the client. 我无法弄清楚如何将stdout / stderr重定向到客户端。 I use execvp to execute the command. 我使用execvp来执行命令。

I think I might have to use dup2? 我想我可能要使用dup2? But I can't figure out how to use it properly. 但我无法弄清楚如何正确使用它。 Any help? 有帮助吗?

You just need to use dup2() to duplicate the socket's file descriptor onto the stderr and stdout file descriptors. 您只需要使用dup2()将套接字的文件描述符复制到stderr和stdout文件描述符上。 It's pretty much the same thing as redirecting to pipes. 这与重定向到管道几乎是一回事。

cpid = fork();
if (cpid == 0) {
  dup2(sockfd, STDOUT_FILENO);
  dup2(sockfd, STDERR_FILENO);
  execvp(...);
  /*... etc. etc. */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM