LibC: Add posix_openpt(), grantpt() and unlockpt()

This makes getting a pseudoterminal pair a little bit more portable.
Note that grantpt() and unlockpt() are currently no-ops, since we've
already granted the pseudoterminal slave to the calling user.

We also accept O_CLOEXEC to posix_openpt(), unlike some systems. :^)
This commit is contained in:
Andreas Kling 2020-02-05 21:17:41 +01:00
parent 6d1740e4be
commit f2a087126c
Notes: sideshowbarker 2024-07-19 09:35:41 +09:00
5 changed files with 58 additions and 6 deletions

View file

@ -202,9 +202,17 @@ int main(int argc, char** argv)
if (chdir(get_current_user_home_path().characters()) < 0)
perror("chdir");
int ptm_fd = open("/dev/ptmx", O_RDWR | O_CLOEXEC);
int ptm_fd = posix_openpt(O_RDWR | O_CLOEXEC);
if (ptm_fd < 0) {
perror("open(ptmx)");
perror("posix_openpt");
return 1;
}
if (grantpt(ptm_fd) < 0) {
perror("grantpt");
return 1;
}
if (unlockpt(ptm_fd) < 0) {
perror("unlockpt");
return 1;
}

View file

@ -52,9 +52,17 @@ void TerminalWrapper::run_command(const String& command)
return;
}
int ptm_fd = open("/dev/ptmx", O_RDWR | O_CLOEXEC);
int ptm_fd = posix_openpt(O_RDWR | O_CLOEXEC);
if (ptm_fd < 0) {
perror("open(ptmx)");
perror("posix_openpt");
ASSERT_NOT_REACHED();
}
if (grantpt(ptm_fd) < 0) {
perror("grantpt");
ASSERT_NOT_REACHED();
}
if (unlockpt(ptm_fd) < 0) {
perror("unlockpt");
ASSERT_NOT_REACHED();
}

View file

@ -746,4 +746,26 @@ char* realpath(const char* pathname, char* buffer)
errno = 0;
return buffer;
}
int posix_openpt(int flags)
{
if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
errno = EINVAL;
return -1;
}
return open("/dev/ptmx", flags);
}
int grantpt(int fd)
{
(void)fd;
return 0;
}
int unlockpt(int fd)
{
(void)fd;
return 0;
}
}

View file

@ -100,4 +100,8 @@ typedef struct {
} ldiv_t;
ldiv_t ldiv(long, long);
int posix_openpt(int flags);
int grantpt(int fd);
int unlockpt(int fd);
__END_DECLS

View file

@ -143,9 +143,19 @@ int main(int argc, char** argv)
return;
}
int ptm_fd = open("/dev/ptmx", O_RDWR);
int ptm_fd = posix_openpt(O_RDWR);
if (ptm_fd < 0) {
perror("open(ptmx)");
perror("posix_openpt");
client_socket->close();
return;
}
if (grantpt(ptm_fd) < 0) {
perror("grantpt");
client_socket->close();
return;
}
if (unlockpt(ptm_fd) < 0) {
perror("unlockpt");
client_socket->close();
return;
}