Reputation: 3986
I've got a socket open, which connects a client and the server.
I'm implementing remote execution, and so I want to change the file descriptor table such that calls which would normally go to stdout, actually go across the socket to be output on the client.
Right now i have the server fork, and then use the system() command to execute whatever command.
What do i have to do to manipulate the file descriptor table?
Here is the code I am working with:
I am using select. The socket I am using is the one returned by the accept call (this is all server side).
dup2(S,1);
int retval = fork();
if (retval > 1)
{
system(receive.text);
return 0;
}
Now the result of this, is that no text is printed to the server (so its obviously not hooked into the stdout of the server), but neither is anything displayed on the client).
Do i have to do anything more on the client side to get this out (like a recv() call?), and am I using the right socket?
Thanks.
Upvotes: 2
Views: 4166
Reputation: 215193
The problem is that system
merely keeps the parent's file descriptors, so it cannot work like you want. You could use popen
, but it's ugly. You really should write the fork
and exec
code yourself. system
is almost always a mistake.
Upvotes: 0
Reputation: 104020
The usual mechanism is dup2(2)
:
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
The dup(2)
call will duplicate the given filedescriptor to the lowest-numbered open filedescriptor. This was the historical mechanism, still works, but it doesn't make it easy to specify file descriptor numbers. So dup2(2)
was introduced to allow specifying both filedescriptors.
You could use it like this:
int s = /* connect() or accept() */
int ret = dup2(s, 1);
/* exec() */
Upvotes: 3