Commit 73027ed2 authored by Michael Hanselmann's avatar Michael Hanselmann
Browse files

utils: Add function to set FD_CLOEXEC on file descriptor



This will be used by another patch adding a utility function to start a daemon.
Signed-off-by: default avatarMichael Hanselmann <hansmi@google.com>
Reviewed-by: default avatarIustin Pop <iustin@google.com>
parent edcb5d9e
......@@ -273,6 +273,25 @@ def _RunCmdFile(cmd, env, via_shell, output, cwd):
return status
def SetCloseOnExecFlag(fd, enable):
"""Sets or unsets the close-on-exec flag on a file descriptor.
@type fd: int
@param fd: File descriptor
@type enable: bool
@param enable: Whether to set or unset it.
"""
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
if enable:
flags |= fcntl.FD_CLOEXEC
else:
flags &= ~fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
def RetryOnSignal(fn, *args, **kwargs):
"""Calls a function again if it failed due to EINTR.
......
......@@ -34,6 +34,7 @@ import shutil
import re
import select
import string
import fcntl
import ganeti
import testutils
......@@ -232,6 +233,23 @@ class TestRunCmd(testutils.GanetiTestCase):
self.failUnlessEqual(RunCmd(["pwd"], cwd=cwd).stdout.strip(), cwd)
class TestSetCloseOnExecFlag(unittest.TestCase):
"""Tests for SetCloseOnExecFlag"""
def setUp(self):
self.tmpfile = tempfile.TemporaryFile()
def testEnable(self):
utils.SetCloseOnExecFlag(self.tmpfile.fileno(), True)
self.failUnless(fcntl.fcntl(self.tmpfile.fileno(), fcntl.F_GETFD) &
fcntl.FD_CLOEXEC)
def testDisable(self):
utils.SetCloseOnExecFlag(self.tmpfile.fileno(), False)
self.failIf(fcntl.fcntl(self.tmpfile.fileno(), fcntl.F_GETFD) &
fcntl.FD_CLOEXEC)
class TestRemoveFile(unittest.TestCase):
"""Test case for the RemoveFile function"""
......@@ -246,25 +264,21 @@ class TestRemoveFile(unittest.TestCase):
os.unlink(self.tmpfile)
os.rmdir(self.tmpdir)
def testIgnoreDirs(self):
"""Test that RemoveFile() ignores directories"""
self.assertEqual(None, RemoveFile(self.tmpdir))
def testIgnoreNotExisting(self):
"""Test that RemoveFile() ignores non-existing files"""
RemoveFile(self.tmpfile)
RemoveFile(self.tmpfile)
def testRemoveFile(self):
"""Test that RemoveFile does remove a file"""
RemoveFile(self.tmpfile)
if os.path.exists(self.tmpfile):
self.fail("File '%s' not removed" % self.tmpfile)
def testRemoveSymlink(self):
"""Test that RemoveFile does remove symlinks"""
symlink = self.tmpdir + "/symlink"
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment