Skip to content

Instantly share code, notes, and snippets.

@aragaer
Created June 27, 2010 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aragaer/454839 to your computer and use it in GitHub Desktop.
Save aragaer/454839 to your computer and use it in GitHub Desktop.
Simple pseudo-terminal app
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <errno.h>
#include <signal.h>
char *path = "/home/aragaer/pts";
char linkname[80] = "";
void sigint(int sig) {
unlink(linkname);
exit(0);
}
int reopen_pseudo(int fd) {
char buf[80];
if (fd < 0) { // first open
int i, res;
struct stat tmp;
for (i = 0; i < 10; i++) {
sprintf(linkname, "%s%d", path, i);
res = stat(linkname, &tmp);
if (res == -1 && errno == ENOENT)
break;
}
if (i == 10) {
printf("No free links found\n");
return -1;
}
} else {
unlink(linkname);
close(fd);
}
fd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (fd == -1)
return fd;
ptsname_r(fd, buf, sizeof buf);
symlink(buf, linkname);
unlockpt(fd);
return fd;
}
int main() {
int fd = -1;
char ch;
signal(SIGINT, sigint);
while ((fd = reopen_pseudo(fd)) > 0) {
while (read(fd, &ch, 1) > 0) {
printf("%c", ch);
fflush(stdout);
}
printf("!\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment