I am trying to redirect STDOUT AND STDERR to a socket.
I did:
if(fork() == 0)
{
dup2(newsock, STDOUT_FILENO);
dup2(newsock, STDERR_FILENO);
execvp();
}
Somehow, it only showed the first little part of the output.
for example, it showed on "mkdir" when I try to execute ls or mkdir.
What's the problem?
I tried the flollowing it works, but I can only redirect one of STDOUT or STDERR
close(1);
dup(newsock);
Thanks a lot.
Read again the
man dup2
page (excerpts):So it should be
dup2 (STDOUT_FILENO, newsock);
Your use of
dup2()
looks fine, so the problem is probably elsewhere. The simple program I threw together to test with does not have the issues you are experiencing, so I'll just go over the core of it (around thefork()
/execvp()
area) with some error checking omitted for brevity:The above is the core of a very basic server (only one client at a time) that, when it receives a connection, forks a new process to run a command and sends its stderr and stdout to the client over the socket. Hopefully you can solve your problem by examining it -- but don't just copy the code without understanding what it does.
Try testing by connecting with a telnet client first... if it works with telnet but not with your client program, then look for problems in your client program.
Your usage of
dup2
is correct. Your write calls are not writing the entire buffer you're giving them, as the data hasn't been received by the remote peer yet, and the kernel buffer allocated for this is likely full. The typical buffer size is 64KB. You should make sure that the receiver is receiving the data, and wrap your writes in a loop. Alternatively useMSG_SENDALL
, and thesend
syscall.