virfile: Introduce virCloseFrom()

It is handy to close all FDs from given FD to infinity. On
FreeBSD the libc even has a function for that: closefrom(). It
was ported to glibc too, but not musl. At least glibc
implementation falls back to calling:

  close_range(from, ~0U, 0);

Now that we have a wrapper for close_range() we implement
closefrom() trivially.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
Reviewed-by: Kristina Hanicova <khanicov@redhat.com>
This commit is contained in:
Michal Privoznik 2023-08-21 15:10:25 +02:00
parent d69237caa3
commit 06d0a66292
3 changed files with 23 additions and 0 deletions

View File

@ -2275,6 +2275,7 @@ saferead;
safewrite;
safezero;
virBuildPathInternal;
virCloseFrom;
virCloseRange;
virCloseRangeInit;
virCloseRangeIsSupported;

View File

@ -265,6 +265,27 @@ virCloseRangeIsSupported(void)
}
/**
* virCloseFrom:
*
* Closes all open file descriptors greater than or equal to @fromfd.
*
* Returns: 0 on success,
* -1 on error (with errno set).
*/
int
virCloseFrom(int fromfd)
{
#ifdef __FreeBSD__
/* FreeBSD has closefrom() since FreeBSD-8.0, i.e. since 2009. */
closefrom(fromfd);
return 0;
#else /* !__FreeBSD__ */
return virCloseRange(fromfd, ~0U);
#endif /* !__FreeBSD__ */
}
/**
* virFileDirectFdFlag:
*

View File

@ -64,6 +64,7 @@ static inline void virForceCloseHelper(int *fd)
int virCloseRange(unsigned int from, unsigned int to);
int virCloseRangeInit(void);
bool virCloseRangeIsSupported(void);
int virCloseFrom(int fromfd);
/* For use on normal paths; caller must check return value,
and failure sets errno per close. */