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?

y3di
  • 673
  • 2
  • 8
  • 13

1 Answers1

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. */
Dmitri
  • 9,175
  • 2
  • 27
  • 34
  • 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? – y3di Nov 10 '11 at 23:49
  • 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. – Dmitri Nov 11 '11 at 02:02
  • 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] – y3di Nov 11 '11 at 02:46
  • 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. – Dmitri Nov 11 '11 at 03:12
  • 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. – y3di Nov 11 '11 at 03:12
  • 1
    @y3di 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! – JJ Liu Nov 11 '11 at 22:38
  • @Dmitri could you please take a look at [this problem](http://stackoverflow.com/questions/8100817/redirect-stdout-and-stderr-to-socket-in-c)? Thanks – JJ Liu Nov 11 '11 at 22:46