Redirect stdout and stderr to socket for a distributed shell program
Asked Answered
O

1

5

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?

Ontario answered 10/11, 2011 at 18:32 Comment(0)
K
7

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. */
Klemm answered 10/11, 2011 at 18:55 Comment(7)
So I tried this method but no output shows up on the client side. But in place of sockfd, I just put the variable of my socket. I'm guessing that's not the actual file descriptor of the socket? How do I actually find out what the file descriptor of the socket is?Ontario
The socket file descriptor (on the server) is the one returned by accept() -- the same one you'd read/write to/from if you weren't using fork()/execvp(). If that's the one you're using, there might be a different problem with your code.Klemm
is there any code I should be doing client side in order for the output to come through? Do I need to do a read() or something of that sort [as if the server was writing something to that port]Ontario
On the client side, it shouldn't be any different from if your server generated the output itself... yes, you'll need to read it somehow (possibly with read()), but you'd have to do that anyway. You might consider using a telnet program to connect to your server to test it out if you're not sure whether your client works properly yet. Also (in the server), make sure to wait() or waitpid() for the child process in the parent process, and close the socket in the parent.Klemm
ok cool, it works now. I just didn't call read() on the client side (I wasn't sure whether redirecting the output with dup2 required a read on the client side). Thanks for all the help.Ontario
@Ontario hello, I am trying to solve the same problem now. I used dup2(newsock, STDOUT_FILENO); dup2(newsock, STDERR_FILENO); but it only output the first lines of output. any ideas? Thanks!Fougere
@Klemm could you please take a look at this problem? ThanksFougere

© 2022 - 2024 — McMap. All rights reserved.