Home > Backend Development > Golang > How to Make a Program Think It\'s Running in a Terminal?

How to Make a Program Think It\'s Running in a Terminal?

Barbara Streisand
Release: 2024-11-29 12:44:09
Original
130 people have browsed it

How to Make a Program Think It's Running in a Terminal?

How to Emulate a TTY for a Program

When a program interacts with stdin, it may behave differently based on whether it is a terminal or a pipe. To overcome this, you can use a technique called "pseudoterminal" (Pty) emulation to make your program appear as a TTY.

One implementation is provided in the C code below, using the forkpty function. This code sets up a pseudoterminal, forks a child process to execute the desired command, and continuously forwards its output to stdout.

#include <signal.h>
#include <stdlib.h>
#include <sysexits.h>
#include <unistd.h>
#include <util.h>

pid_t child = 0;

void sighandler(int signum) {
  if (child > 0) {
    killpg(child, signum);
    exit(signum);
  }
}

int main(int argc, char *argv[]) {
  if (argc < 2) {
    return EX_USAGE;
  }

  int master;
  child = forkpty(&amp;master, NULL, NULL, NULL);

  if (child == -1) {
    perror("failed to fork pty");
    return EX_OSERR;
  }

  if (child == 0) {
    execvp(argv[1], argv + 1);
    perror("failed to execute command");
    return EX_OSERR;
  }

  signal(SIGHUP, sighandler);
  signal(SIGINT, sighandler);
  signal(SIGTERM, sighandler);

  const int buf_size = 1024;
  char buf[buf_size];
  fd_set fds;
  ssize_t bytes_read;

  while (1) {
    FD_ZERO(&amp;fds);
    FD_SET(master, &amp;fds);

    if (select(master + 1, &amp;fds, NULL, NULL, NULL) > 0 &amp;&amp; FD_ISSET(master, &amp;fds)) {
      bytes_read = read(master, buf, buf_size);
      if (bytes_read <= 0) {
        return EXIT_SUCCESS;
      }

      if (write(STDOUT_FILENO, buf, bytes_read) != bytes_read) {
        perror("failed to write to stdout");
        return EX_OSERR;
      }
    }
  }
}
Copy after login

By integrating this technique, your program can effectively interact with other applications as if it were operating through a terminal.

The above is the detailed content of How to Make a Program Think It\'s Running in a Terminal?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template