我目前正在开发 ssh 程序,我希望能够通过网络完全控制终端。我的问题是,如果我向服务器发送命令以在终端中运行,如何获取终端打印的输出?我看到很多帖子说要使用popen()
命令,但根据我的尝试,我无法更改目录并使用它执行其他命令,只能执行简单的操作,例如ls
。除了将其发送到类似文件之外,还有其他方法可以从终端获取输出吗command > filetoholdcommand
。提前致谢!
我会将其作为评论,但由于我是新人,所以我没有足够的代表。 cd 是一个内置的 shell 命令,因此您需要使用 system()。但是 cd 对你的进程没有影响(你必须使用 chdir() ),所以你真正想做的是通过 fork/exec 启动一个 shell 作为子进程,将管道连接到它的 stdin 和 stdout,然后在用户会话或连接期间通过管道传递命令。
以下代码给出了总体思路。基本的,但有缺陷的 - 使用 select() 而不是 usleep() 作为其中之一。
int argc2;
printf( "Server started - %d\n", getpid() );
char buf[1024] = {0};
int pid;
int pipe_fd_1[2];
int pipe_fd_2[2];
pipe( pipe_fd_1 );
pipe( pipe_fd_2 );
switch ( pid = fork() )
{
case -1:
exit(1);
case 0: /* child */
close(pipe_fd_1[1]);
close(pipe_fd_2[0]);
dup2( pipe_fd_1[0], STDIN_FILENO );
dup2( pipe_fd_2[1], STDOUT_FILENO );
execlp("/bin/bash", "bash", NULL);
default: /* parent */
close(pipe_fd_1[0]);
close(pipe_fd_2[1]);
fcntl(pipe_fd_2[0], F_SETFL, fcntl(pipe_fd_2[0], F_GETFL, NULL ) | O_NONBLOCK );
while(true)
{
int r = 0;
printf( "Enter cmd:\n" );
r = read( STDIN_FILENO, &buf, 1024 );
if( r > 1 )
{
buf[r] = '\0';
write(pipe_fd_1[1], &buf, r);
}
usleep(100000);
while( ( r = read( pipe_fd_2[0], &buf, 1024 ) ) > 0 )
{
buf[r-1] = '\0';
printf("%s", buf );
}
printf("\n");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)