1

我正在尝试在代表 PTY 的文件描述符上设置读取超时。我在 termios 中设置了 VMIN = 0 和 VTIME = 10,我希望在字符可用时返回,或者如果没有字符可用则在一秒钟后返回。但是,我的程序永远处于读取调用中。

PTY 有什么特别之处使它不起作用吗?是否有其他 TERMIOS 设置导致此设置起作用?我在标准输入文件描述符上尝试了相同的配置,它按预期工作。

#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>

#define debug(...) fprintf (stderr, __VA_ARGS__)

static void set_term (int fd)
{
    struct termios termios;
    int res;

    res = tcgetattr (fd, &termios);
    if (res) {
        debug ("TERM get error\n");
        return;
    }

    cfmakeraw (&termios);
    termios.c_lflag &= ~(ICANON);
    termios.c_cc[VMIN] = 0;
    termios.c_cc[VTIME] = 10;        /* One second */

    res = tcsetattr (fd, TCSANOW, &termios);
    if (res) {
        debug ("TERM set error\n");
        return;
    }

}

int get_term (void)
{
    int fd;
    int res;
    char *name;

    fd = posix_openpt (O_RDWR);
    if (fd < 0) {
        debug ("Error opening PTY\n");
        exit (1);
    }

    res = grantpt (fd);
    if (res) {
        debug ("Error granting PTY\n");
        exit (1);
    }

    res = unlockpt (fd);
    if (res) {
        debug ("Error unlocking PTY\n");
        exit (1);
    }

    name = ptsname (fd);
    debug ("Attach terminal on %s\n", name);

    return fd;
}

int main (int argc, char **argv)
{
    int read_fd;
    int bytes;
    char c;

    read_fd = get_term ();

    set_term (read_fd);
    bytes = read (read_fd, &c, 1);
    debug ("Read returned\n");

    return 0;
}
4

1 回答 1

0

从 linux pty(7) 联机帮助页(斜体是我的):

伪终端(有时缩写为“pty”)是一对提供双向通信通道的虚拟字符设备。通道的一端称为主机;另一端称为奴隶。 伪终端的从端提供了一个行为与经典终端完全相同的接口

但是,您的程序正在从master读取,不能期望它的行为与终端设备完全相同

如果您更改/扩展最后几行,那么get_term...

int slave_fd =  open (name, O_RDWR); /* now open the slave end..*/
if (slave_fd < 0) {
   debug ("Error opening slave PTY\n");
   exit (1);
}

return slave_fd; /* ... and use it instead of the master..*/

...您的示例程序将按预期工作。

于 2012-05-26T17:56:10.047 回答