write(2) on a pipe or FIFO can return fewer bytes than requested.
This happens when a blocking write gets interrupted by a signal
after part of the buffer already went through: the kernel hands
back the partial count instead of -EINTR. safe_write() treated any
non-negative return as complete and passed that short count
straight back to the caller.
snd_pcm_file_write_bytes() then saw err != n, broke out of its
write loop, and returned success anyway, so the unwritten tail of
the period never reached the target file.
Writes to a FIFO block waiting for a reader far more often than
writes to a regular file do, which is exactly why the file plugin
only drops samples on pipes and works fine on plain files.
Make safe_write() loop until every byte is written or a real error
turns up.
Closes: https://github.com/alsa-project/alsa-lib/pull/521
Fixes: https://github.com/alsa-project/alsa-lib/issues/63
Signed-off-by: Krishnanand G <krishnanandgeetheswaran@gmail.com>
Signed-off-by: Jaroslav Kysela <perex@perex.cz>
static ssize_t safe_write(int fd, const void *buf, size_t len)
{
- while (1) {
- ssize_t r = write(fd, buf, len);
+ const char *ptr = buf;
+ size_t left = len;
+
+ /*
+ * write(2) to a pipe/FIFO is allowed to return fewer bytes than
+ * requested, e.g. when a blocking write is interrupted by a
+ * signal after part of the data has already been transferred.
+ * Keep retrying until everything is written (or a real error
+ * occurs), otherwise the caller silently drops the remainder.
+ */
+ while (left > 0) {
+ ssize_t r = write(fd, ptr, left);
if (r < 0) {
if (errno == EINTR)
continue;
return -EIO;
return -errno;
}
- return r;
+ if (r == 0)
+ break;
+ ptr += r;
+ left -= r;
}
+ return len - left;
}
static int snd_pcm_file_append_value(char **string_p, char **index_ch_p,