从C中的终端获取所有输出 [英] Getting all output from terminal in C

查看:130
本文介绍了从C中的终端获取所有输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发ssh程序,并且希望能够通过网络完全控制终端.我的问题是,如果我向服务器发送命令以在终端中运行,如何获得终端打印的输出?我已经看到很多帖子说要使用popen()命令,但是从我尝试过的内容来看,我无法更改目录并使用此命令执行其他命令,只能使用诸如ls之类的简单内容.除了将其发送到command > filetoholdcommand之类的文件之外,还有其他方法可从终端获取输出.预先感谢!

I am currently working on a ssh program and I want to be able to have full control over the terminal via networking. My question is, if I send a command to the server to run in the terminal, how do I get the output that the terminal prints? I have seen many posts saying to use the popen() command but from what I have tried I can't change directories and do other commands using this, only simple things such as ls. Is there any other way to get output from terminal besides sending it to a file like command > filetoholdcommand. Thanks in advance!

推荐答案

我会将其作为注释,但是由于我是新手,所以没有足够的代表. cd是一个内置的shell命令,因此您想使用system().但是cd对您的进程没有影响(为此,您必须使用chdir()),因此您真正想要做的是通过fork/exec将shell作为子进程启动,将管道连接到stdin和stdout,然后在用户会话或连接期间通过管道传输命令.

I would put this as a comment, but I dont have enough rep as I'm new. cd is a built in shell command so you want to use system(). But cd will have no effect on your process (you have to use chdir(), for that),so what you really want to do is start a shell as a subprocess via fork/exec, connect pipes to it stdin and stdout,then pipe it commands for the duration of the user session or connection.

以下代码给出了总体思路.基本且有缺陷-使用select()而不是usleep().

Following code give the general idea. Basic, and flawed - use select() not usleep() for one.

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");
    }
}

这篇关于从C中的终端获取所有输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆