2012-05-25 115 views
1

我試圖設置表示PTY的文件描述符的讀取超時。我在termios中設置了VMIN = 0和VTIME = 10,我希望在字符可用時返回,如果沒有可用字符,則在秒後返回。但是,我的程序永遠坐在閱讀電話中。pty文件描述符失敗的讀取超時

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

回答

0

從Linux pty(7)用戶手冊(斜體字是礦):

甲僞終端(有時縮寫爲 「PTY」)是一對虛擬角色設備的那 提供一個雙向通信信道。該頻道的一端稱爲 主;另一端稱爲奴隸。 從屬結束僞終端的提供 ,其行爲酷似經典終端的接口

你的程序,但是,從讀取主,不能預期到完全一樣的終端裝置

如果你改變/擴大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..*/ 

...您的示例程序將按預期工作。

+0

當然,這引出了爲什麼Faz原始程序中* master *上的tcsetattr()成功以及它達到了什麼樣的問題。我相信(但無法在任何地方找到此文件)它設置* slave *終端屬性。在任何情況下,只要讀取是在從機端完成的,示例程序中用於tcsetattr()的兩個文件描述符中的哪一個不會影響其行爲。 –

+0

更多關於Solaris和Linux上的master和slave的區別[這裏](https://blogs.oracle.com/weixue/entry/tip_differece_master_pty_regards) –

相關問題