Having more than one process read from a serial device (/dev/ttyXX) makes it so that both processes can't get all of the data -- the data will be split between them in some way. I'd like to write a program that reads from a serial device, creates several master/slave pty pairs, and then allows programs that were made to read from the serial device to instead read from the ptys so that all reading processes receive the data from the serial device and have the ptys act like the serial device in the sense that when they start reading from the pty they get only the most recent data. In other words, you won't get any data that was written before you started to read (it's my experience that this is how /dev/ttyXX devices work, or at least the RS-232 anemometer I'm reading from). Named pipes can mimic these semantics by trapping SIGPIPE to determine that there is no reader and thus we can choose not to write to that particular named pipe. However, some binaries that were written to use terminals may fail when talking to named pipes, as checks for isatty() and the errno condition on calls like tcsetattr() can cause failing conditions. The key here is to be able to use existing binaries that were written for a terminal.
So, if I can detect when the slave side of the pty is opened for reading, this should give me roughly the same semantics as there being no SIGPIPE in the named pipe case. I notice that HP-UX has TIOCTRAP as an ioctl() command which seems to do exactly what I want, but sadly it is not available on Linux.
I've been reading references for days and the number of options for this type of thing is staggering. The answer might lie in the terminal settings, blocking/non-blocking behavior, setting buffer sizes somewhere, conditions reported from poll()/select(), or some combination. I can't seem to find anything, though. I'm wondering if it's possible that I need to write my own device driver, but it seems like I should be able to do this without going that far.
So, for clarification:
- The question is: How can I detect when someone opens the slave side of a pty (pseudo-terminal) in Linux?
- I want a reader opening the slave side of the pty to receive data written strictly after the reader opens the pty (if my multi-writing process just writes data for a while before the reader opens the slave side, the data will buffer up and eventually the writer will block and the slave reader, upon opening, will immediately get all the buffered data -- this is not desirable as I want it to get only data generated in the immediate temporal vicinity)
- It must be a pty, not a named pipe, socket, etc, as isatty() and tcsetattr(), etc need to be OK so that existing binaries work