0

I have two processes communicating via a pty, nonblocking. Problem is that the fread() on the master fails when there is no data available to process.

How can I ignore the "no reader/data present" case when reading from the unconnected file descriptor on the master side? I suspect there is some flag for open() or fcntl() which I skipped during reading?

// initialization:
int pty_fd = posix_openpt(O_RDWR | O_NOCTTY);
int rc = grantpt(pty_fd);
rc = unlockpt(pty_fd);
fcntl(pty_fd, F_SETFL, O_NONBLOCK);
fd_read = fdopen(pty_fd, "r");

// now, trying to read will fail if no data is present:
char buf[100];
int count = sizeof(buf);
size_t bytesRead = fread(buf, sizeof(char), count, fd_read);
if ((bytesRead == 0) && (ferror(fd_read)) {
    printf("fail...\n");
}

Sure, I can ignore the return value of ferror(), but I suppose this is not the right way to use this function.

Ah, one thing: I found the POLLHUP trick on stackoverflowz. It works but is racy and hence not suitable for my case...

Greetings

Community
  • 1
  • 1
klsdjfhsalkjfhl
  • 173
  • 1
  • 10
  • What do you expect/want fread to return in such case? – n. m. could be an AI Jan 19 '16 at 17:19
  • Zero, as it does. But I would expect `ferror()` to not be true... – klsdjfhsalkjfhl Jan 19 '16 at 17:23
  • Requesting some bytes and receiving less bytes *is* either an eof or an error condition, by definition. You need to examine errno to see what kind of error it is, and decide how to handle it. – n. m. could be an AI Jan 19 '16 at 17:38
  • It's probably not a good idea to use stdio with ptys or other special fd types that have transient EOF or error conditions when you actually want to treat those conditions as transient. There are ways to make it work, but working directly with file descriptors usually makes more sense. – R.. GitHub STOP HELPING ICE Jan 19 '16 at 17:52
  • @n.m. Is it an error even when I said O_NONBLOCK? How can I distinguish between "no bytes present" (I'm Ok with that) and "the world is on fire" (should probably call exit now...)? – klsdjfhsalkjfhl Jan 19 '16 at 18:26
  • I would guess it is an error by definition, the definition being "whenever the underlying POSIX I/O layer sets errno" (probably EAGAIN in this case). – n. m. could be an AI Jan 19 '16 at 19:44
  • ha, somehow I did not notice that errno is set anyways, even by fread... stupid me... – klsdjfhsalkjfhl Jan 20 '16 at 11:32

0 Answers0