7

The slave fd is used by another application (say "A") as a serial port device .

A will set its baud rate/stop bit etc. My app needs this information .

BTW, is there any way for a process that has only the master fd open to be notified of all ioctl() calls that are issued to the slave fd ?

Hans Lub
  • 5,513
  • 1
  • 23
  • 43
Shazoo
  • 73
  • 5

1 Answers1

9

Yes, this is possible (in Linux and pre-2004 FreeBSD) , using the pty in packet mode and setting the EXTPROC flag on it.

  • Packet mode is enabled on the master end by ioctl(master, TIOCPKT, &nonzero). Now every read on the master end will yield a packet: whatever was written on the other side, plus a status byte that says something about the situation on the slave end ("The write queue for the terminal (i.e. the slave end) is flushed")

  • This doesn't mean, however, that the master is immediately aware of changes on the slave end, e.g. a select() on the master will not return as soon as those changes happen, only when there is something to read

  • However, after setting EXTPROC in the pty's local flag word - using tcsetattr() - select() will return as soon as the slave state changes, and one can then inspect the slaves termios - either directly via the slave fd which we keep open in the parent process, or, on linux at least, simply by tcgetattr() on the master side.

  • Note that EXTPROC disables certain parts of the pty driver, e.g. local echoing is turned off.

EXTPROC is not used a lot (here is a possible use case), not very portable and not documented at all (it shoud at least have been somewhere in the linux termios or tty_ioctl manpages). Looking at the linux kernel source drivers/tty/n_tty.c I conclude that any change in the slaves termios structure will make the select() on the master end return - but a tcsetattr() that doesn't change anything won't.

Edit: in response to J.F. Sebastians's request below I give an example program that should make clear how to use EXTRPOC in packet mode on a linux machine:

/* Demo program for managing a pty in packet mode with the slave's
** EXTPROC bit set, where the master gets notified of changes in the
** slaves terminal attributes
**   
** save as extproc.c, compile with gcc -o extproc extproc.c -lutil
*/



#include <stdio.h>
#include <pty.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

#define BUFSIZE 512

void main() {
  int master;      // fd of master side
  pid_t pid;
  if((pid = forkpty(&master, NULL, NULL, NULL))) { // we're parent
    fd_set rfds, xfds;
    int retval, nread, status = 0, nonzero = 1;
    char buf[BUFSIZE];

    ioctl(master, TIOCPKT, &nonzero); // initiate packet mode - necessary to get notified of
                                      // ioctl() on the slave side
    while(1) {
      // set stdout unbuffered (we want to see stuff as it happens)                                                                                 
      setbuf(stdout, NULL);

      // prepare the file descriptor sets
      FD_ZERO(&rfds);
      FD_SET(master, &rfds);

      FD_ZERO(&xfds);
      FD_SET(master, &xfds);

      // now wait until status of master changes     
      printf("---- waiting for something to happen -----\n");
      select(1 + master, &rfds, NULL, &xfds, NULL);

      char *r_text = (FD_ISSET(master, &rfds) ? "master ready for reading" : "- ");
      char *x_text = (FD_ISSET(master, &xfds) ? "exception on master" : "- ");

      printf("rfds: %s, xfds: %s\n", r_text, x_text);
      if ((nread = read(master, buf, BUFSIZE-1)) < 0) 
        perror("read error");
      else {         
        buf[nread] = '\0';
        // In packet mode *buf will be the status byte , and buf + 1 the "payload"
        char *pkt_txt = (*buf &  TIOCPKT_IOCTL ? " (TIOCPKT_IOCTL)" : "");
        printf("read %d bytes: status byte %x%s, payload <%s>\n", nread, *buf, pkt_txt, buf + 1);
      }
      if (waitpid(pid, &status, WNOHANG) && WIFEXITED(status)) {
        printf("child exited with status %x\n", status);
        exit(EXIT_SUCCESS);
      } 
    }
  } else { // child
    struct termios tio;

    // First set the EXTPROC bit in the slave end termios structure
    tcgetattr(STDIN_FILENO, &tio);
    tio.c_lflag |= EXTPROC;
    tcsetattr(STDIN_FILENO, TCSANOW, &tio); 

    // Wait a bit and do an ordinary write()
    sleep(1);
    write(STDOUT_FILENO,"blah", 4);

    // Wait a bit and change the pty terminal attributes. This will be picked up by the master end
    sleep(1);
    tio.c_cc[VINTR] = 0x07; 
    tcsetattr(STDIN_FILENO, TCSANOW, &tio);

    // Wait a bit and exit
    sleep(1);
  } 
}

The output will be something like:

---- waiting for something to happen -----
rfds: master ready for reading, xfds: exception on master
read 1 bytes: status byte 40 (TIOCPKT_IOCTL), payload <>
---- waiting for something to happen -----
rfds: master ready for reading, xfds: - 
read 5 bytes: status byte 0, payload <blah>
---- waiting for something to happen -----
rfds: master ready for reading, xfds: exception on master
read 1 bytes: status byte 40 (TIOCPKT_IOCTL), payload <>
---- waiting for something to happen -----
rfds: master ready for reading, xfds: - 
read error: Input/output error
child exited with status 0

In general, the master end of a pty need not be a tty (and have an associated termios structure), but under Linux, it is (with a shared termios: changes on one end will change both termios structures at the same time).

This means that we can modify the example program above and set EXTPROC on the master side, it won't make any difference.

All of this is not documented as far as I can see, and even less portable, of course.

Hans Lub
  • 5,513
  • 1
  • 23
  • 43
  • Could you provide some reference for the statements in the answer? How did you find out about TIOCPKT, EXTPROC, select() behavior with a pty? – jfs Jul 03 '17 at 09:53
  • @J.F.Sebastian: I modified my answer above by including an example program. I dont't remember how I found out about `TIOCPKT` and `EXTPROC`: they are hardly mentioned on the Web (and apparently not much used nowadays) – Hans Lub Jul 17 '17 at 09:57
  • 1- I've got `read error` line first (due to stdout buffering. Disabling it (`setvbuf(stdout, NULL, _IONBF, 0);`) produces expected output) 2- [setting EXTPROC only in the parent doesn't produce notifications on my Linux machine](https://gist.github.com/zed/71bc51d8968dc04f44076596ec5f73ef) – jfs Jul 17 '17 at 15:56
  • @J.F.Sebastian: **1** By default, stdout [should be line buffered](https://stackoverflow.com/questions/3723795/is-stdout-line-buffered-unbuffered-or-indeterminate-by-default) in linux. I added `setbuf(stdout, NULL)` just to be certain. **2** I think you made a mistake there: you set `EXTPROC` on `stdin` instead of `master` – Hans Lub Jul 17 '17 at 19:59
  • 1- If stdout is a pipe; [it may be fully buffered](https://stackoverflow.com/q/20503671/4279). For some reason a compilation buffer in emacs used a pipe instead of a pty in this case. It is my mistake that I didn't notice it and didn't check in a terminal. 2- The "stdin instead of master" is even more embarrassing. I've fixed it and it works as described in the answer. I should have gone to bed 8 hours ago. Sorry for the noise. – jfs Jul 18 '17 at 00:08
  • Don't worry: I'm glad you took the time to check it all, and that I'm not the only one making such mistakes... – Hans Lub Jul 18 '17 at 06:37
  • With packet mode, is the additional byte at start only in master end (not in slave) ? Thanks, – ransh Jan 03 '19 at 10:07
  • @ransh: You are right. As the manpage for [ioctl_tty](http://man7.org/linux/man-pages/man2/ioctl_tty.2.html) states: _Can be applied to the master side of a pseudoterminal only_. It would wreak havoc if the `ioctl()` on the master side would make the slave end read en extra byte for each `read()`, so the effect of the `ioctl()` is _only_ visible at the master end – Hans Lub Jan 03 '19 at 13:28
  • @Hans: Thanks, one more if I may. I see on above answer that EXTPROC is configured for slave stdin, but isn't it supposed to be configured for master fd ? (as you wrote in one of the comments above) – ransh Jan 03 '19 at 14:31
  • 1
    No, `TIOCPKT` has to be set on the master, but `EXTPROC` _should_ be configured on the slave end like in the example code above. I only observed that on a linux machine, master and slave appear to share their `termios` structure (at least back then) so that the EXTPROC can be set on the master side as well. All this is undocumented and not portable, in other words: not recommended! – Hans Lub Jan 03 '19 at 15:13