美文网首页
C编程 - 伪终端(PTY)的一个例子

C编程 - 伪终端(PTY)的一个例子

作者: louyang | 来源:发表于2018-05-26 13:55 被阅读13次
    image.png
    /*
     * An example of pseudo terminal
     */
    
    #define _GNU_SOURCE
    #include <stdlib.h>   //xxxpt()
    #include <fcntl.h>    //O_RDWR
    #include <stdio.h>    //fprintf()
    #include <errno.h>    //perror(),errno
    #include <unistd.h>   //read(),write(),fork(),open(),close()
    #include <termios.h>
    
    
    int main(void)
    {
        int fdm, fds, rc;
        char input[150];
    
        fdm = posix_openpt(O_RDWR);
        if (fdm < 0) {
            perror("when posix_openpt() pty-master");
            return 1;
        }
    
        rc = unlockpt(fdm);
        if (rc != 0) {
            perror("when unlockpt() pty-master");
            return 1;
        }
    
        fds = open(ptsname(fdm), O_RDWR);
        if (fds < 0) {
            perror("when open() pty-slave");
            return 1;
        }
    
        if (fork()) { // Father
            close(fds);
    
            while (1) {
                write(1, "Input : ", sizeof("Input : "));
                rc = read(0, input, sizeof(input)-1);
                if (rc > 0) {
                    write(fdm, input, rc);
    
                    rc = read(fdm, input, sizeof(input)-1);
                    if (rc > 0) {
                        fprintf(stdout, "111-%s", input);
                    }
                    else
                        break;
                }
                else
                    break;
            }
        }
        else { // Child
            close(fdm);
    
            struct termios settings;
            rc = tcgetattr(fds, &settings);
            cfmakeraw (&settings);
            tcsetattr (fds, TCSANOW, &settings);
    
            dup2(fds, 0);
            dup2(fds, 1);
            dup2(fds, 2);
    
            while (1)
            {
               rc = read(0, input, sizeof(input) - 1);
               if (rc > 0) {
                   input[rc - 1] = '\0';
                   fprintf(stdout, "222-%s\n", input);
               }
               else
                   break;
            }
        }
    
        return 0;
    }
    
    $ gcc a.c && ./a.out
    Input : aaa
    111-222-aaa
    Input : bbb
    111-222-bbb
    
    参考

    http://rachid.koucha.free.fr/tech_corner/pty_pdip.html

    相关文章

      网友评论

          本文标题:C编程 - 伪终端(PTY)的一个例子

          本文链接:https://www.haomeiwen.com/subject/skeyjftx.html