From 91ce76af9d6c86e77acb1f2cdb9cd9aad5847f16 Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Thu, 10 Aug 2017 11:54:26 +0200 Subject: [PATCH] system/FileDescriptor: add methods EnableCloseOnExec(), DisableCloseOnExec() --- src/system/FileDescriptor.cxx | 20 +++++++++++++++++++- src/system/FileDescriptor.hxx | 14 +++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/system/FileDescriptor.cxx b/src/system/FileDescriptor.cxx index 7fef7ed6b..4e4365cf9 100644 --- a/src/system/FileDescriptor.cxx +++ b/src/system/FileDescriptor.cxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2015 Max Kellermann + * Copyright (C) 2012-2017 Max Kellermann * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -126,6 +126,24 @@ FileDescriptor::SetBlocking() noexcept fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); } +void +FileDescriptor::EnableCloseOnExec() noexcept +{ + assert(IsDefined()); + + const int old_flags = fcntl(fd, F_GETFD, 0); + fcntl(fd, F_SETFD, old_flags | FD_CLOEXEC); +} + +void +FileDescriptor::DisableCloseOnExec() noexcept +{ + assert(IsDefined()); + + const int old_flags = fcntl(fd, F_GETFD, 0); + fcntl(fd, F_SETFD, old_flags & ~FD_CLOEXEC); +} + #endif #ifdef USE_EVENTFD diff --git a/src/system/FileDescriptor.hxx b/src/system/FileDescriptor.hxx index af05fd1fb..57ffba3cf 100644 --- a/src/system/FileDescriptor.hxx +++ b/src/system/FileDescriptor.hxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2015 Max Kellermann + * Copyright (C) 2012-2017 Max Kellermann * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -114,6 +114,18 @@ public: */ void SetBlocking() noexcept; + /** + * Auto-close this file descriptor when a new program is + * executed. + */ + void EnableCloseOnExec() noexcept; + + /** + * Do not auto-close this file descriptor when a new program + * is executed. + */ + void DisableCloseOnExec() noexcept; + /** * Duplicate the file descriptor onto the given file descriptor. */