简体   繁体   中英

Find free port to Open Pseudo Terminal Using BSD

I want to create a Pseudo Terminal using the BSD API. My understanding is that the Unix 98 API will automatically find a free port with posix_openpt() but with BSD API I need to check/find a free port to connect to. Is this correct?

So I need to do something like this...?

int fd, index = 0;
char serial_port[11]; // = "/dev/ptyp0"

while (true) {
    sprintf(serial_port, "/dev/ptyp%d", index); 
    fd = open(serial_port, O_RDWR | O_NOCTTY | O_NONBLOCK);

    if (fd > 0) 
        break;

    index++;
}

Do you know of a Pseudo Terminal tutorial that uses BSD? There are many using Unix 98 API but not many if any BSD API ones.

Using the actual device path is problematic because the pathnames can differ from system to system. Most portable applications which use pseudo terminals long ago were changed to use one of the library functions written to abstract away from the device path.

There is more than one flavor of BSD to consider, eg, FreeBSD, NetBSD, OpenBSD (and others of course, including OSX). xterm's configure script identifies features from each. All have openpty in the "util" library, providing its prototype in util.h

POSIX provides posix_openpt which combines the functionality of openpty with others to provide a simpler interface. However (though a documented interface), it is known to not work properly with OSX (see for example OSX 10.7.5 UTF-8 encoding over ssh as well as xterm's changelog ).

Here are manpage links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM