compat: add function to enable nonblocking pipes

We'd like to be able to make some of our pipes nonblocking so that
poll() can be used effectively, but O_NONBLOCK isn't portable. Let's
introduce a compat wrapper so this can be abstracted for each platform.

The interface is as narrow as possible to let platforms do what's
natural there (rather than having to implement fcntl() and a fake
O_NONBLOCK for example, or having to handle other types of descriptors).

The next commit will add Windows support, at which point we should be
covering all platforms in practice. But if we do find some other
platform without O_NONBLOCK, we'll return ENOSYS. Arguably we could just
trigger a build-time #error in this case, which would catch the problem
earlier. But since we're not planning to use this compat wrapper in many
code paths, a seldom-seen runtime error may be friendlier for such a
platform than blocking compilation completely. Our test suite would
still notice it.

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Jeff King 2022-08-17 02:04:55 -04:00 committed by Junio C Hamano
parent ad60dddad7
commit 10f743389c
3 changed files with 33 additions and 0 deletions

View File

@ -910,6 +910,7 @@ LIB_OBJS += combine-diff.o
LIB_OBJS += commit-graph.o
LIB_OBJS += commit-reach.o
LIB_OBJS += commit.o
LIB_OBJS += compat/nonblock.o
LIB_OBJS += compat/obstack.o
LIB_OBJS += compat/terminal.o
LIB_OBJS += compat/zlib-uncompress2.o

23
compat/nonblock.c Normal file
View File

@ -0,0 +1,23 @@
#include "git-compat-util.h"
#include "nonblock.h"
#ifdef O_NONBLOCK
int enable_pipe_nonblock(int fd)
{
int flags = fcntl(fd, F_GETFL);
if (flags < 0)
return -1;
flags |= O_NONBLOCK;
return fcntl(fd, F_SETFL, flags);
}
#else
int enable_pipe_nonblock(int fd)
{
errno = ENOSYS;
return -1;
}
#endif

9
compat/nonblock.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef COMPAT_NONBLOCK_H
#define COMPAT_NONBLOCK_H
/*
* Enable non-blocking I/O for the pipe specified by the passed-in descriptor.
*/
int enable_pipe_nonblock(int fd);
#endif