Preserving progress after interrupted reads

A Linux data collector reads a 960-byte record from a blocking pipe. Its signal handler returns normally, preserves errno, and does not access the pipe or buffer. The handler was installed without SA_RESTART.


The proposed recovery code is below. The buffer holds 960 bytes, the required declarations and headers are supplied, and errno initially equals EINTR.


C
size_t done = 0;
while (done != 960) {
    ssize_t n = read(fd, buf + done, 960 - done);
    if (n > 0) {
        done += (size_t)n;
    } else if (n == -1 && errno == EINTR) {
        done = 0;
        continue;
    } else {
        break;
    }
}


The first five calls produce these observed results. Each failure is caused by a caught signal before that call transfers any bytes.


Call

Return value n

errno after return

1

240

EINTR

2

-1

EINTR

3

180

EINTR

4

-1

EINTR

5

300

EINTR


Find the byte count passed to the sixth read call as written. Then find the byte count that should be passed if the EINTR branch preserves earlier progress instead of resetting done. For the corrected version, assume the same first five return values. Give both counts in bytes as exact integers.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Signal Handling Questions: