在子进程中将所有用户输入转发到 Linux PTY

如何解决在子进程中将所有用户输入转发到 Linux PTY

背景

我正在尝试为 shell 构建一个包装器。在 TTY 中运行,它通过 forkpty 在子进程中生成常规 shell。目的是将所有用户输入按原样转发到子进程,但要拦截子进程的输出并对其进行一些处理,然后再将其复制到父进程'stderr .除了增强的输出之外,用户应该能够忘记外壳是完全包装的。

问题

我不知道如何透明地转发输入。这是我当前代码的要点(省略了错误检查和次要细节)。它应该用 gcc <filename> -pthread -lutil:

编译
#include <stdbool.h>
#include <stdio.h>
#include <errno.h>

#include <pthread.h>
#include <signal.h>
#include <pty.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUF_SIZE 512
#define EOT "\x04"    // ASCII end-of-transmission (i.e. 'EOF').

void * tty_input_routine(void * arg);
void   tty_output_routine();
int    parent_term_fd;

volatile sig_atomic_t got_sigchld = 0;
volatile sig_atomic_t got_sigwinch = 0;
// Listens for the child to exit,and causes the parent to exit.
void handle_sigchld(int sig) {
    got_sigchld = 1;
}
// Listens for the parent to be resized,and causes the child to be resized.
void handle_sigwinch(int sig) {
    got_sigwinch = 1;
}

void main() {
    /* Block SIGWINCH and SIGCHLD. They are later unblocked via pselect in the main loop. */
    sigset_t sigmask;
    sigemptyset(&sigmask);
    sigaddset(&sigmask,SIGWINCH);    
    sigaddset(&sigmask,SIGCHLD);
    sigprocmask(SIG_BLOCK,&sigmask,NULL);

    /* Establish signal handlers. */
    struct sigaction sig_action;
    sig_action.sa_flags = 0;
    sig_action.sa_handler = &handle_sigchld;
    sigemptyset(&sig_action.sa_mask);
    sigaction(SIGCHLD,&sig_action,NULL);
    sig_action.sa_handler = &handle_sigwinch;
    sigaction(SIGWINCH,NULL);

    /* Get the initial terminal size. */
    struct winsize term_sz;
    ioctl(STDERR_FILENO,TIOCGWINSZ,&term_sz);

    /* Turn off input echo in the child terminal since the parent should do that. */
    struct termios term_ios;
    tcgetattr(STDERR_FILENO,&term_ios);
    term_ios.c_lflag &= ~(ECHO);

    /* Do the fork. */
    pid_t child_pid = forkpty(&parent_term_fd,NULL,&term_ios,&term_sz);
    if (child_pid == 0) {
        /* This is the child process. Execute the shell. */
        char *const argv[] = { NULL };
        execvp("/bin/bash",argv);
    }
    /* This is the parent process.
     * Spawn a dedicated thread to forward input to the child PTY.
     * The main thread will be used to process the output. */
    pthread_t input_thread;
    pthread_create(&input_thread,&tty_input_routine,NULL);
    tty_output_routine(parent_term_fd);
}

void * tty_input_routine(void * arg) {
    struct termios tcattr;
    tcgetattr(STDIN_FILENO,&tcattr);
    // cfmakeraw(&tcattr);                         // This doesn't seem to help.
    // tcattr.c_lflag &= ~ICANON;                  // Neither does this...
    tcsetattr(STDIN_FILENO,TCSAFLUSH,&tcattr);

    char buf[BUF_SIZE];
    fd_set fds;
    FD_ZERO(&fds);
    while (true) {
        FD_SET(STDIN_FILENO,&fds);
        if (select(STDIN_FILENO + 1,&fds,NULL) == -1) {
            if (errno == EINTR) {
                continue;  // A signal was caught; just try again.
            }
            // Otherwise,some error...
            puts("THIS IS UNEXPECTED");
            break;
        } else {
            ssize_t bytes = read(STDIN_FILENO,buf,BUF_SIZE);
            if (bytes > 0) {
                write(parent_term_fd,(size_t)bytes);                               
            } else if (bytes == 0) {
                /* End of transmission? */
                write(parent_term_fd,EOT,1);
                break;
            }
        }
    }
    return NULL;
}

void tty_output_routine() {
    fd_set fds;
    FD_ZERO(&fds);
    sigset_t empty_sigmask;
    sigemptyset(&empty_sigmask);
    char buf[BUF_SIZE];

    while (true) {
        FD_SET(parent_term_fd,&fds);
        if (pselect(parent_term_fd + 1,&empty_sigmask) == -1) {
            if (errno == EINTR) {
                /* A signal was caught. */
                if (got_sigwinch) {
                    got_sigwinch = 0;
                    struct winsize term_sz;
                    ioctl(STDERR_FILENO,&term_sz);
                    /* This sends SIGWINCH to the child. */
                    ioctl(parent_term_fd,TIOCSWINSZ,&term_sz);
                }
                if (got_sigchld) {
                    // This should run when the user does CTRL+D,but it doesn't...
                    puts("THIS IS THE PROPER EXIT");
                    return;
                }
            } else {
                // Otherwise,some error...
                break;
            }
        } else {
            ssize_t bytes = read(parent_term_fd,BUF_SIZE);
            // (Omitted) do some processing on the buffer.
            write(STDERR_FILENO,(size_t)bytes);
        }
    
    }
}
  • 这个想法是,当用户点击CTRL+D时,输入例程会读取一个空缓冲区,并将EOT发送给子进程,子进程将退出,导致SIGCHLD在父级中触发,它也将退出。但是,SIGCHLD 永远不会在父级中引发,即使 bash 肯定会退出,正如它在屏幕上打印 exit 的事实所示。令人困惑的是,SIGWINCH 似乎处理得很好。

  • 此外,父级无法将 CTRL+C 转发给子级。即使我为 SIGTERM 添加另一个信号处理程序并简单地通过 kill 将该信号转发给子进程,shell 本身也会退出,而不是 shell 中正在运行的任何东西,就像 bash 通常所做的那样。我不知道这里有什么不同。

  • 我尝试过 cfmakeraw 并关闭规范模式 (ICANON) 但这会使程序更加崩溃。也许我还缺少其他一些终端属性?

感觉就像我过度设计了这个,因为我想要做的本质上就是欺骗子进程接受输入,就好像它没有包装父进程一样。我真的必须在父级中明确处理所有内容并手动将用户输入和信号转发给子级吗?除了增强的输出之外,我如何才能以用户无法判断外壳已包装的方式执行此操作?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-