Created
November 16, 2024 16:00
-
-
Save franklindyer/c9b1840342ab205be297e6d0c38483e1 to your computer and use it in GitHub Desktop.
Minimal example usage of /dev/ptmx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
int main() { | |
int master_tty = open("/dev/ptmx", O_RDWR); | |
if (master_tty < 0) { | |
fprintf(stderr, "MASTER: could not open /dev/ptmx.\n"); | |
exit(1); | |
} | |
char* slave_name = ptsname(master_tty); | |
if (slave_name == NULL) { | |
fprintf(stderr, "MASTER: could not get name of slave device.\n"); | |
exit(1); | |
} | |
printf("MASTER: slave device %s created\n", slave_name); | |
if (grantpt(master_tty) < 0 || unlockpt(master_tty) < 0) { | |
fprintf(stderr, "MASTER: could not grant access to the slave device.\n"); | |
exit(1); | |
} | |
int slave_tty = open(slave_name, O_RDWR); | |
if (slave_tty < 0) { | |
fprintf(stderr, "MASTER: could not open %s\n", slave_name); | |
exit(1); | |
} | |
int pid; | |
if ((pid = fork()) > 0) { | |
// Parent code | |
close(slave_tty); | |
char c[2] = {'x', '\n'}; // Note that without the newline, the line buffer won't be flushed | |
printf("MASTER: sending character %c\n", c[0]); | |
if (write(master_tty, &c, 2) < 0) { | |
fprintf(stderr, "MASTER: could not write to master end of TTY\n"); | |
exit(1); | |
} | |
waitpid(-1, NULL, 0); | |
printf("MASTER: exiting\n"); | |
exit(0); | |
} else { | |
// Child code | |
close(master_tty); | |
char c; | |
if (read(slave_tty, &c, 1) < 0) { | |
fprintf(stderr, "SLAVE: could not read from %s\n", slave_name); | |
exit(1); | |
} | |
printf("SLAVE: received character %c\n", c); | |
printf("MASTER: exiting\n"); | |
exit(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment