Last active
February 19, 2024 17:10
-
-
Save punzik/1f0093b36b06c2817f08de7383503b86 to your computer and use it in GitHub Desktop.
Print to terminal via pts
This file contains hidden or 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
#define _GNU_SOURCE | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <signal.h> | |
#include <string.h> | |
volatile int running = 1; | |
void ctrlc_handler(int unused) | |
{ | |
running = 0; | |
} | |
int main(void) { | |
int ptx, pts; | |
char *pts_path; | |
char tmp_str[256]; | |
int err = -1; | |
signal(SIGINT, ctrlc_handler); | |
int ptmx = open("/dev/ptmx", O_RDWR | O_NOCTTY); | |
if (ptmx == -1) { | |
printf("Open ptmx fail\n"); | |
goto error0; | |
} | |
if (unlockpt(ptmx) != 0) { | |
printf("Unlock ptmx fail"); | |
goto error1; | |
} | |
if (grantpt(ptmx) != 0) { | |
printf("Grant ptmx fail"); | |
goto error1; | |
} | |
pts_path = ptsname(ptmx); | |
pts = open(pts_path, O_WRONLY | O_NOCTTY); | |
if (pts == -1) { | |
printf("Open pts fail\n"); | |
goto error1; | |
} | |
snprintf(tmp_str, 256, "-S%s/%d", pts_path, ptmx); | |
switch(fork()) { | |
case -1: | |
printf("Fork error\n"); | |
goto error2; | |
case 0: | |
execl("/usr/bin/xterm", "xterm", tmp_str, (char*)NULL); | |
return 0; | |
} | |
for (int n = 0; (n < 1000) && running; n ++) { | |
snprintf(tmp_str, 256, "Fork: N = %i\n", n); | |
if (write(pts, tmp_str, strlen(tmp_str) + 1) == -1) { | |
printf("Write to pts error\n"); | |
goto error2; | |
} | |
printf("Main: N = %i\n", n); | |
sleep(1); | |
} | |
err = 0; | |
error2: | |
close(pts); | |
error1: | |
close(ptmx); | |
error0: | |
return err; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment