[Lldb-commits] [lldb] [lldb] Keep the inferior's terminal open until LLDB read its output (PR #229387)

Raphael Isemann via lldb-commits lldb-commits at lists.llvm.org
Tue Oct 6 04:47:06 PDT 2026


Teemperor wrote:

I let Claude hack together a demo program that demonstrates the data loss we're seeing:

```cpp
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <poll.h>
#include <string>
#include <sys/wait.h>
#include <unistd.h>

static void die(const char *what) {
  std::perror(what);
  std::exit(1);
}

// Reads whatever is currently available on fd without blocking for long.
static std::string drain(int fd) {
  std::string result;
  while (true) {
    pollfd pfd{fd, POLLIN, 0};
    int ready = poll(&pfd, 1, /*timeout_ms=*/200);
    if (ready <= 0)
      break;
    char buf[256];
    ssize_t n = read(fd, buf, sizeof(buf));
    if (n <= 0) {
      // EIO is what reading the primary returns once no secondary is open.
      if (n < 0 && errno != EIO)
        die("read");
      break;
    }
    result.append(buf, n);
  }
  return result;
}

static std::string escape(const std::string &s) {
  std::string out;
  for (char c : s) {
    if (c == '\n')
      out += "\\n";
    else if (c == '\r')
      out += "\\r";
    else
      out += c;
  }
  return out;
}

static void run(bool keep_secondary) {
  int primary = posix_openpt(O_RDWR | O_NOCTTY);
  if (primary < 0)
    die("posix_openpt");
  if (grantpt(primary) != 0 || unlockpt(primary) != 0)
    die("grantpt/unlockpt");
  std::string secondary_path = ptsname(primary);

  int secondary = -1;
  if (keep_secondary) {
    secondary = open(secondary_path.c_str(), O_RDWR | O_NOCTTY | O_CLOEXEC);
    if (secondary < 0)
      die("open secondary");
  }

  pid_t pid = fork();
  if (pid < 0)
    die("fork");
  if (pid == 0) {
    // Child: make the secondary side stdout, write a line, exit.
    close(primary);
    int fd = open(secondary_path.c_str(), O_RDWR | O_NOCTTY);
    if (fd < 0)
      die("child open secondary");
    dup2(fd, STDOUT_FILENO);
    close(fd);
    const char msg[] = "hello from the child\n";
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    _exit(0);
  }

  // Parent: wait until the child (and its secondary descriptors) are gone
  // before reading anything.
  int status;
  if (waitpid(pid, &status, 0) < 0)
    die("waitpid");

  std::string output = drain(primary);
  std::printf("%-26s read %2zu bytes: \"%s\"\n",
              keep_secondary ? "secondary kept open:" : "secondary not kept open:",
              output.size(), escape(output).c_str());

  if (secondary >= 0)
    close(secondary);
  close(primary);
}

int main() {
  run(/*keep_secondary=*/false);
  run(/*keep_secondary=*/true);
}
```

https://github.com/llvm/llvm-project/pull/229387


More information about the lldb-commits mailing list