簡體   English   中英

Linux中Pseudo Terminal的讀寫問題

[英]Read Write issues with Pseudo Terminal in Linux

我正在編寫一個C ++程序,它將與外部進程進行交互。 外部過程是用C#編寫的,並且在mono上運行。 請注意,我不能修改C#代碼,因為它不是我編寫的程序。

在這方面,我首先使用管道進行了設置,后來我意識到它是完全緩沖的,因此我遇到了很多同步問題。 本質上,外部進程必須在每次寫入后刷新其輸出,而這是不可能的。

我接下來要嘗試的是文件,但是我發現使用偽終端會更適合我的情況。 這是我編寫的一些示例代碼:

int main()
{
    int fdm, fds, rc, pid;
    bool rValue;
    /* Setup Master pty*/
    rValue = rValue && (fdm = posix_openpt(O_RDWR)) >= 0 &&
             (rc = grantpt(fdm)) == 0 && (rc = unlockpt(fdm) == 0);
    if (rValue) {
        /* Open Slave pty */
        fds = open(ptsname(fdm), O_RDWR);
        pid = fork();
        if(pid < 0)
            perror("fork failed");
        else if(pid == 0) //child
        {
            close(fdm); //close master
            struct termios slave_orig_term_settings;
            struct termios new_term_settings;
            tcgetattr(slaveTTY, &slave_orig_term_settings);
            new_term_settings = slave_orig_term_settings;
            cfmakeraw(&new_term_settings);
            tcsetattr(slaveTTY, TCSANOW, &new_term_settings);

            //redirect I/O of this process
            close(0);
            close(1);
            close(2);
            dup(slaveTTY);
            dup(slaveTTY);
            dup(slaveTTY);

            close(slaveTTY);

            setsid();
            ioctl(0, TIOCSCTTY, 1);

            //launch the external process and replace its image in this process
            execve(argv[0],...);
        }
        else
        {
            close(fds); //close slave
            //Perform some interaction
            write(something using fdm);
            //Assume fdsets declared and set somewhere here
            select(fdm +1,&fdset,NULL,NULL,NULL);
            int readBytes = read(someting using fds);
        }
    }
    return EXIT_SUCCESS;
}

假設正在處理用於選擇的fdset和fdclr。

在父流程中觀察到以下問題:

  1. 有時讀取返回readBytes> 0,但緩沖區中不存在任何內容
  2. 有時會讀回已寫入終端的任何內容
  3. 一些垃圾值,例如^]] 49] 1R正在轉儲到終端上(這是實際的終端,即我的輸出窗口)

PS:使用C / C ++編寫外部進程時,不會發生此問題。 僅當我在mono中運行C#程序時。

我認為,如果您不必在C++這樣做,則python中的pexpect是一個不錯的選擇,它將節省大量時間。 此外,您還可以使用pyinstaller等python凍結工具將python腳本轉換為獨立的二進制文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM