c - Linux:写一个C程序,那个 'controls'一个shell

标签 c linux shell controls

假设我们有一个 shell 在终端上运行,比方说,/dev/pts/1。 shell 已经在运行,我们无法重新启动它。

现在我们要编写一个 C 程序来“控制”shell,即它本身会为用户提供一个类似 shell 的界面,读取用户的输入,将其传递到/dev/pts/上的真实 shell 1,让它执行它,读取 shell 的输出并将其打印回给用户。

我知道如何完成这项任务的一半:我知道如何收集用户的输入并将此输入注入(inject)“真实 shell ”:

#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>

#define SIZE 100

int main(int argc, char** argv)
{
if( argc>1 )
  {
  int tty = open( argv[1], O_WRONLY|O_NONBLOCK);

  if( tty!=-1 )
    {
    char *buf,buffer[SIZE+1];

    while(1)
      {
      printf("> ");
      fgets( buffer, SIZE, stdin );
      if( buffer[0]=='q' && buffer[1]=='u' && buffer[2]=='i' && buffer[3]=='t' ) break;
      for(buf=buffer; *buf!='\0'; buf++ ) ioctl(tty, TIOCSTI, buf);
      }

    close(tty);
    }
  else printf("Failed to open terminal %s\n", argv[1]);
  }

return 0;
}

上面的代码会将您的输入传递给在终端中运行的 shell(在第一个参数中给出其名称)并让 shell 执行它。但是,我现在不知道如何读取 shell 的输出。

有什么建议吗?

最佳答案

您可以使用 pipes为了那个原因。 Linux shell 允许重定向。

我使用管道来控制 tty。

关于c - Linux:写一个C程序,那个 'controls'一个shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747306/

相关文章:

linux - 在 Eclipse 中设置 bash 脚本

python - 相当于 Linux 上的 GetTickCount()

linux - 如何比较两个列表的第一个词并打印匹配条目的第二个词?

c - 使用 C windows 8 关闭屏幕

c - 在 C 语言中使用 lapack

c - OpenGL 照明斗争

java - Maven 命令 mvn 从终端运行没有错误,但从 python 没有错误

c - 获取给定进程的 STARTUPINFO

linux - 如何在复制操作系统磁盘后在 Azure ASM 中保留/设置默认管理员密码

linux - execlp 用户库函数