capture: add some portability fallbacks

If we're on non-Linux, we can use some portability fallbacks to
get similar behavior to Linux. I'm sure we can optimize this a
bit more for FreeBSD if someone with that installed wants to
come look at things and improve them.
This commit is contained in:
Christian Hergert
2019-05-06 20:04:17 -07:00
parent 607ef387e7
commit ac1767eff2
2 changed files with 217 additions and 69 deletions

View File

@ -24,79 +24,34 @@
#ifdef __linux__
# include <sys/sendfile.h>
#endif
#include <errno.h>
#include <unistd.h>
#ifdef __linux__
# define _sp_sendfile sendfile
# define _sp_getpagesize getpagesize
# define _sp_pread pread
# define _sp_pwrite pwrite
# define _sp_write write
# define _sp_getpid getpid
# define _sp_sendfile sendfile
#else
static inline ssize_t
_sp_sendfile (int out_fd,
int in_fd,
off_t *offset,
size_t count)
{
ssize_t total = 0;
off_t wpos = 0;
off_t rpos = 0;
errno = 0;
if (offset != NULL && *offset > 0)
wpos = rpos = *offset;
while (count > 0)
{
unsigned char buf[4096*4];
ssize_t n_written = 0;
ssize_t n_read;
off_t off = 0;
size_t to_read;
/* Try to page align */
if ((rpos % 4096) != 0)
to_read = 4096 - rpos;
else
to_read = sizeof buf;
if (to_read > count)
to_read = count;
errno = 0;
n_read = pread (in_fd, buf, to_read, rpos);
if (n_read <= 0)
return -1;
g_assert (count >= n_read);
count -= n_read;
rpos += n_read;
while (wpos < rpos)
{
g_assert (off < sizeof buf);
errno = 0;
n_written = write (out_fd, &buf[off], rpos - wpos);
if (n_written <= 0)
return -1;
wpos += n_written;
off += n_written;
total += n_written;
}
}
g_assert (count == 0);
if (offset != NULL)
*offset = rpos;
errno = 0;
return total;
}
size_t _sp_getpagesize (void);
ssize_t _sp_pread (int fd,
void *buf,
size_t count,
off_t offset);
ssize_t _sp_pwrite (int fd,
const void *buf,
size_t count,
off_t offset);
ssize_t _sp_write (int fd,
const void *buf,
size_t count);
gint32 _sp_getpid (void);
ssize_t _sp_sendfile (int out_fd,
int in_fd,
off_t *offset,
size_t count);
#endif
#endif /* SP_CAPTURE_UTIL_PRIVATE_H */