Reading with pty

I would like to receive (and later process) write(1) and wall(1) ) messages using pseudo-language (Unix 98) on Linux. I already have the following minimal implementation:

 #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <utempter.h> #define BUF_LENGTH 1024 int main (void) { FILE *lf; int masterfd, slavefd; char *slave_name = NULL; char buf[BUF_LENGTH]; size_t nbytes = sizeof(buf); ssize_t bytes_read; int exit_code = EXIT_SUCESS; if ((masterfd = posix_openpt (O_RDWR | O_NOCTTY)) == -1 || grantpt (masterfd) == -1 || unlockpt (masterfd) == -1 || (slave_name = ptsname (masterfd)) == NULL) exit (EXIT_FAILURE); if (!(lf = fopen("term.log","w"))) exit (EXIT_FAILURE); addToUtmp (slave_name, NULL, masterfd); for (;;) { bytes_read = read(masterfd, buf, nbytes); if (bytes_read <= 0) break fwrite (buf, 1, bytes_read, lf); } if (bytes_read < 0) { fprintf (stderr, "error reading from master pty: %s\n", strerror (errno)); exit_code = EXIT_FAILURE; } fclose (lf); if (slavefd >= 0) close (slavefd); if (masterfd >= 0) { removeLineFromUtmp (slave_name, masterfd); close (masterfd); } exit (exit_code); } 

The problem is that it only works for reading the first message, and then reading gives me an EIO error. Why is this?

+4
source share
1 answer

This seems to happen simply when the last file descriptor of the sub file is closed. Given that write(1) and wall(1) will have a single file descriptor for the slave, you will get EIO as soon as you finish writing.

The easiest way to avoid this is to save the file descriptor. Right after your ptsname call run open(slave_name, O_RDRW) .

(Curiously, you already have the slavefd variable and code to clear it. Are you testing us ?: p)

+1
source

Source: https://habr.com/ru/post/1311882/


All Articles