繁体   English   中英

如何检测分配的终端设备进行交互式工作

[英]How detect assigned terminal device for interactive work

我正在写寻呼机pspg 我必须解决以下问题。 stdin读取后,我应该将stdin从之前从管道读取到终端读取。

我用了

freopen("/dev/tty", "r", stdin) 

但是,当从命令中使用寻呼机时,它不起作用

su - someuser -c 'export PAGER=pspg psql somedb'

在这种情况下,我收到一个错误: 没有这样的设备或地址

我找到了一个解决方法 - 现在,代码看起来像:

if (freopen("/dev/tty", "r", stdin) == NULL)
{
    /*
     * try to reopen pty.
     * Workaround from:
     * https://cboard.cprogramming.com/c-programming/172533-how-read-pipe-while-keeping-interactive-keyboard-c.html
     */
    if (freopen(ttyname(fileno(stdout)), "r", stdin) == NULL)
    {
        fprintf(stderr, "cannot to reopen stdin: %s\n", strerror(errno));
        exit(1);
    }
}

在这种情况下,检测分配的终端设备的正确方法是什么?

但这种解决方法不正确。 它解决了一个问题,但接下来就要来了。 当某个用户与当前用户不同时,重新打开失败,并显示“ 权限被拒绝”错误。 因此,此解决方法不能用于我的目的。

在这种情况下, less是回到fd 2(stderr)。 如果stderr已被重定向远离tty,它会放弃尝试获取键盘输入,并且只打印整个输入流而不进行分页。

su的设计不允许任何更好的东西。 新用户正在原始用户拥有的tty上运行命令,并且不能完全隐藏该令人不快的事实。

这是su的一个很好的替代品,没有这个问题:

ssh -t localhost -l username sh -c 'command'

当然,它有更多的开销。

最后我使用了我在less寻呼机中找到的模式,但修改后使用ncurses

首先,我试图重新打开标准输入一些TTY相关的设备:

if (!isatty(fileno(stdin)))
{
    if (freopen("/dev/tty", "r", stdin) != NULL)
        noatty = false;
    /* when tty is not accessible, try to get tty from stdout */ 
    else if (freopen(ttyname(fileno(stdout)), "r", stdin) != NULL)
        noatty = false;
    else
    {
        /*
         * just ensure stderr is joined to tty, usually when reopen
         * of fileno(stdout) fails - probably due permissions.
         */
        if (!isatty(fileno(stderr)))
        {
            fprintf(stderr, "missing a access to terminal device\n");
            exit(1);
        }
        noatty = true;
        fclose(stdin);
    }
}                   
else
    noatty = false;

当我没有tty并且不能使用stdin ,那么我正在使用newterm函数,它允许指定输入流:

if (noatty)
    /* use stderr like stdin. This is fallback solution used by less */
    newterm(termname(), stdout, stderr);
else
    /* stdin is joined with tty, then use usual initialization */
    initscr();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM