2015-10-20 25 views
2

屏幕的應用程序連接我想創建C/C++應用程序,在的/ dev/XXX創造了新的(虛擬)設備,並能夠與「屏幕」應用程序連接。如何創建PTY是由Linux的

對於循環中運行的示例程序中,創建新的/ dev/ttyABC。然後我會使用'screen/dev/ttyABC',當我發送一些字符時,然後應用程序將它發送回'屏幕'。

我真的不知道從哪裏開始。我在pty庫上找到了一些引用,但我甚至不知道,如果我有正確的方向。

你能幫我嗎?去哪裏看?後例子? 謝謝

回答

1

您可以通過openpty使用Pseudoterminal來實現此目的。 openpty回報的一對通過其stdout/stdin彼此連接文件描述符(主從pty設備)。一個的輸出將出現在另一個的輸入處,反之亦然。

使用這種(粗!)例如...

#include <fcntl.h> 
#include <cstdio> 
#include <errno.h> 
#include <pty.h> 
#include <string.h> 
#include <unistd.h> 

int main(int, char const *[]) 
{ 
    int master, slave; 
    char name[256]; 

    auto e = openpty(&master, &slave, &name[0], nullptr, nullptr); 
    if(0 > e) { 
    std::printf("Error: %s\n", strerror(errno)); 
    return -1; 
    } 

    std::printf("Slave PTY: %s\n", name); 

    int r; 

    while((r = read(master, &name[0], sizeof(name)-1)) > 0) { 
    name[r] = '\0'; 
    std::printf("%s", &name[0]); 
    } 

    close(slave); 
    close(master); 

    return 0; 
} 

...呼應一些文字(在另一個終端會話)的從屬pty將它發送到master的輸入。例如。 echo "Hello" > /dev/pts/2

+0

它工作的罰款,直到我試圖與屏幕連接。 但是,當我連接到代碼一些mmaped文件行爲像/ dev/tty設備,它可以工作。我是對的,不是嗎? – Payne

+0

我不確定你可以直接將'screen'連接到slave pty。 – gmbeard

+0

Becouse,我想創建一些文件加入奴隸pty ..這就是我需要的 - 屏幕可連接的文件/流..是否有一些可能性使它? – Payne

0

基於由@gmbeard提供的答案,我能創造一個回聲PTY裝置和屏幕的Minicom連接到它。通過初始化termios結構來使用原始PTY設備的原因是什麼。

下面是代碼

#include <string.h> 
#include <unistd.h> 
#include <errno.h> 
#include <cstdio> 
#include <pty.h> 
#include <termios.h> 

#define BUF_SIZE (256) 

int main(int, char const *[]) 
{ 
    int master, slave; 
    char buf[BUF_SIZE]; 
    struct termios tty; 
    tty.c_iflag = (tcflag_t) 0; 
    tty.c_lflag = (tcflag_t) 0; 
    tty.c_cflag = CS8; 
    tty.c_oflag = (tcflag_t) 0; 

    auto e = openpty(&master, &slave, buf, &tty, nullptr); 
    if(0 > e) { 
    std::printf("Error: %s\n", strerror(errno)); 
    return -1; 
    } 

    std::printf("Slave PTY: %s\n", buf); 

    int r; 

    while ((r = read(master, buf, BUF_SIZE)) > 0) 
    { 
     write(master, buf, r); 
    } 

    close(slave); 
    close(master); 

    return 0; 
} 
+0

是的,你是對的。我現在修好了 –