Closing slave end of PTY device loses data unless slave descriptor closed in parent.

Edward Lee e45lee at
Sat Dec 31 00:46:35 UTC 2016


I'm seeing some interesting behaviour from the following snippet of code,
taken from here:

On Linux, the code blocks on the final read but produces both lines of
output.  However on FreeBSD, the final line of output is sometimes
lost (consistently on a single-core machine).  Is there a particular
reason for this, or is this a bug?

For reference, this was run on a single-core FreeBSD 11 virtual machine.


#include <stdio.h>
#include <unistd.h>
#include <libutil.h>

/* save as test.c and compile with cc -o test test.c -lutil */

#define BUFSIZE 255

int main(void) {
  int master, slave;
  char buf[BUFSIZE];
  int nread;

  openpty(&master, &slave, NULL, NULL, NULL);

  if (fork()) {       /* parent:
    close(slave);     /* leave this out and lose slave's final words
... WHY?         */
    do {
      nread = read(master, buf, BUFSIZE);
      write(STDOUT_FILENO, buf, nread); /* echo child's output to
stdout              */
    } while (nread > 0);
  } else {             /* child:
    login_tty(slave);  /* this makes child a session leader and slave
a controlling   */
                       /* terminal for it, then dup()s std{in,out,err}
to slave       */
    printf("Feeling OK :-)\n");
    printf("Feeling unwell ... Arghhh!\n"); /* this line may get lost
  return 0;

More information about the freebsd-questions mailing list