diff mbox series

[v2] redir: savefd: use F_DUPFD_CLOEXEC instead of F_DUPFD+F_SETFD, if available

Message ID 20230105124321.gsmk7h7xpuss75hw@tarta.nabijaczleweli.xyz (mailing list archive)
State Accepted
Delegated to: Herbert Xu
Headers show
Series [v2] redir: savefd: use F_DUPFD_CLOEXEC instead of F_DUPFD+F_SETFD, if available | expand

Commit Message

Ahelenia Ziemiańska Jan. 5, 2023, 12:43 p.m. UTC
This saves a syscall on every source file open, &c.;
F_DUPFD_CLOEXEC is a mandatory part of POSIX since Issue 7
(Austin Group Interpretation 1003.1-2001 #171).
---
 configure.ac | 11 +++++++++++
 src/redir.c  |  7 ++++++-
 2 files changed, 17 insertions(+), 1 deletion(-)

Comments

Ahelenia Ziemiańska Jan. 5, 2023, 12:45 p.m. UTC | #1
(this is v3 with your comments applied, naturally; my finger slipped)

наб
Herbert Xu Jan. 8, 2023, 12:06 p.m. UTC | #2
On Thu, Jan 05, 2023 at 01:43:21PM +0100, наб wrote:
> This saves a syscall on every source file open, &c.;
> F_DUPFD_CLOEXEC is a mandatory part of POSIX since Issue 7
> (Austin Group Interpretation 1003.1-2001 #171).
> ---
>  configure.ac | 11 +++++++++++
>  src/redir.c  |  7 ++++++-
>  2 files changed, 17 insertions(+), 1 deletion(-)

Patch applied.  Thanks.
diff mbox series

Patch

diff --git a/configure.ac b/configure.ac
index 52aa429..5524650 100644
--- a/configure.ac
+++ b/configure.ac
@@ -177,6 +177,17 @@  if test "$have_st_mtim" = "yes"; then
 		[Define if your `struct stat' has `st_mtim'])
 fi
 
+dnl F_DUPFD_CLOEXEC is a mandatory part of POSIX since Issue 7
+AC_MSG_CHECKING(for F_DUPFD_CLOEXEC)
+AC_COMPILE_IFELSE(
+[AC_LANG_PROGRAM([#include <unistd.h>
+#include <fcntl.h>],
+[return fcntl(0, F_DUPFD_CLOEXEC, 0)])],
+have_dupfd_cloexec=1, have_dupfd_cloexec=0)
+AC_MSG_RESULT($(expr yes \& $have_dupfd_cloexec \| no))
+AC_DEFINE_UNQUOTED([HAVE_F_DUPFD_CLOEXEC], [$have_dupfd_cloexec],
+	[Define to 1 your system supports F_DUPFD_CLOEXEC])
+
 AC_ARG_WITH(libedit, AS_HELP_STRING(--with-libedit, [Compile with libedit support]))
 use_libedit=
 if test "$with_libedit" = "yes"; then
diff --git a/src/redir.c b/src/redir.c
index 5a5835c..631ddc9 100644
--- a/src/redir.c
+++ b/src/redir.c
@@ -446,13 +446,18 @@  savefd(int from, int ofd)
 	int newfd;
 	int err;
 
+#if HAVE_F_DUPFD_CLOEXEC
+	newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
+#else
 	newfd = fcntl(from, F_DUPFD, 10);
+#endif
+
 	err = newfd < 0 ? errno : 0;
 	if (err != EBADF) {
 		close(ofd);
 		if (err)
 			sh_error("%d: %s", from, strerror(err));
-		else
+		else if(!HAVE_F_DUPFD_CLOEXEC)
 			fcntl(newfd, F_SETFD, FD_CLOEXEC);
 	}