Skip to content

Commit 06cd821

Browse files
i2yvasily-v-ryabov
authored andcommitted
Avoid to use fcntl module on some environments
1 parent b091980 commit 06cd821

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

Xlib/support/unix_connect.py

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,23 +23,6 @@
2323
import os
2424
import platform
2525
import socket
26-
27-
# FCNTL is deprecated from Python 2.2, so only import it if we doesn't
28-
# get the names we need. Furthermore, FD_CLOEXEC seems to be missing
29-
# in Python 2.2.
30-
31-
import fcntl
32-
33-
if hasattr(fcntl, 'F_SETFD'):
34-
F_SETFD = fcntl.F_SETFD
35-
if hasattr(fcntl, 'FD_CLOEXEC'):
36-
FD_CLOEXEC = fcntl.FD_CLOEXEC
37-
else:
38-
FD_CLOEXEC = 1
39-
else:
40-
from FCNTL import F_SETFD, FD_CLOEXEC
41-
42-
4326
from Xlib import error, xauth
4427

4528

@@ -93,11 +76,13 @@ def _get_tcp_socket(host, dno):
9376
s.connect((host, 6000 + dno))
9477
return s
9578

79+
9680
def _get_unix_socket(address):
9781
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9882
s.connect(address)
9983
return s
10084

85+
10186
def get_socket(dname, protocol, host, dno):
10287
assert protocol in SUPPORTED_PROTOCOLS
10388
try:
@@ -127,11 +112,37 @@ def get_socket(dname, protocol, host, dno):
127112
raise error.DisplayConnectionError(dname, str(val))
128113

129114
# Make sure that the connection isn't inherited in child processes.
130-
fcntl.fcntl(s.fileno(), F_SETFD, FD_CLOEXEC)
115+
_ensure_not_inheritable(s)
131116

132117
return s
133118

134119

120+
def _ensure_not_inheritable(sock):
121+
# According to PEP446, in Python 3.4 and above,
122+
# it is not inherited in child processes by default.
123+
# However, just in case, we explicitly make it non-inheritable.
124+
# Also, we don't use the code like the following,
125+
# because there would be no possibility of backporting to past versions.
126+
# if sys.version_info.major == 3 and sys.version_info.minor >= 4:
127+
# sock.set_inheritable(False)
128+
# return
129+
# We just check if the socket has `set_inheritable`.
130+
if hasattr(sock, 'set_inheritable'):
131+
sock.set_inheritable(False)
132+
return
133+
134+
# On Windows,
135+
# Python doesn't support fcntl module because Windows doesn't have fcntl API.
136+
# At least by not importing fcntl, we will be able to import python-xlib on Windows.
137+
if platform.system() == 'Windows':
138+
# so.. unfortunately, for Python 3.3 and below, on Windows,
139+
# we can't make sure that the connection isn't inherited in child processes for now.
140+
return
141+
142+
import fcntl
143+
fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)
144+
145+
135146
def new_get_auth(sock, dname, protocol, host, dno):
136147
assert protocol in SUPPORTED_PROTOCOLS
137148
# Translate socket address into the xauth domain

0 commit comments

Comments
 (0)