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

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


Hi,

I'm seeing some interesting behaviour from the following snippet of code,
taken from here:
https://stackoverflow.com/questions/23458160/final-output-on-slave-pty-is-lost-if-it-was-not-closed-in-parent-why

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.

Thanks,
Edward
----

#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");
    sleep(1);
    printf("Feeling unwell ... Arghhh!\n"); /* this line may get lost
               */
  }
  return 0;
}


More information about the freebsd-questions mailing list