gpt4 book ai didi

linux - pty 文件描述符读取超时失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:55 25 4
gpt4 key购买 nike

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

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

#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;
}

最佳答案

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

A pseudoterminal (sometimes abbreviated "pty") is a pair of virtual character devices that provide a bidirectional communication channel. One end of the channel is called the master; the other end is called the slave. The slave end of the pseudoterminal provides an interface that behaves exactly like a classical terminal

但是,您的程序正在从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..*/

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

关于linux - pty 文件描述符读取超时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10758641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com