stdout和stderr重定向到交流电插座? [英] Redirect STDOUT and STDERR to socket in C?
问题描述
我试图输出和错误重定向到一个插座。
I am trying to redirect STDOUT AND STDERR to a socket.
我所做的:
if(fork() == 0)
{
dup2(newsock, STDOUT_FILENO);
dup2(newsock, STDERR_FILENO);
execvp();
}
不知何故,只显示输出的第一少部分。
Somehow, it only showed the first little part of the output.
例如,这表明在mkdir当我尝试执行ls或MKDIR。
for example, it showed on "mkdir" when I try to execute ls or mkdir.
这是什么问题?
我想它的工作flollowing,但我只能重定向stdout或stderr之一
I tried the flollowing it works, but I can only redirect one of STDOUT or STDERR
close(1);
dup(newsock);
非常感谢。
推荐答案
您使用 dup2的()
看起来不错,所以这个问题可能是在其他地方。简单的程序我扔连同测试没有你所遇到的问题,所以我就投奔它的核心(围绕叉()
/ execvp()
区)的一些错误检查不再赘述:
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 the fork()
/execvp()
area) with some error checking omitted for brevity:
int lsock, /* listening socket */
csock; /* active connection's socket */
pid_t cpid; /* child process ID from fork() */
char *cmd = "somecommand";
char *cmd_args[] = { "somecommand",
"firstarg",
"secondarg",
"howevermanyargs",
NULL }; /* note: last item is NULL */
/* ...
call socket(), bind(), listen(), etc.
... */
for (;;) { /* loop, accepting connections */
if ( (csock = accept( lsock, NULL, NULL )) == -1) exit(1);
cpid = fork();
if (cpid < 0) exit(1); /* exit if fork() fails */
if ( cpid ) {
/* In the parent process: */
close( csock ); /* csock is not needed in the parent after the fork */
waitpid( cpid, NULL, 0 ); /* wait for and reap child process */
} else {
/* In the child process: */
dup2( csock, STDOUT_FILENO ); /* duplicate socket on stdout */
dup2( csock, STDERR_FILENO ); /* duplicate socket on stderr too */
close( csock ); /* can close the original after it's duplicated */
execvp( cmd, cmd_args ); /* execvp() the command */
}
}
上面的是一个非常基本的服务器(只有一个客户端在一时间)的核心,当它接收到一个连接,叉一个新的进程运行的命令和在插座发送其stderr和标准输出到客户端。希望你可以通过检查它解决您的问题 - 但不要只复制code不理解它做什么。
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.
通过Telnet客户端第一连接尝试的测试......如果它与远程登录,但不与你的客户端程序,然后寻找自己的客户端程序的问题。
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.
这篇关于stdout和stderr重定向到交流电插座?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!