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

发布于 2024-12-15 08:53:27 字数 171 浏览 3 评论 0原文

我制作了一个具有客户端和服务器的分布式 shell 程序。客户端向服务器发送命令请求,服务器在本地执行该命令,并将该命令的结果输出给客户端。我无法弄清楚如何将 stdout/stderr 重定向到客户端。我使用 execvp 来执行命令。

我想我可能必须使用 dup2 ?但我不知道如何正确使用它。有什么帮助吗?

I made a distributed shell program that has a client and server. 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. I use execvp to execute the command.

I think I might have to use dup2? But I can't figure out how to use it properly. Any help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

闻呓 2024-12-22 08:53:27

您只需使用 dup2() 将套接字的文件描述符复制到 stderr 和 stdout 文件描述符上。这与重定向到管道几乎是一样的。

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

You just need to use dup2() to duplicate the socket's file descriptor onto the stderr and stdout file descriptors. 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. */
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文