Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions ipykernel/parentpoller.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,19 @@ def run(self):
# We cannot use os.waitpid because it works only for child processes.
from errno import EINTR

# before start, check if the passed-in parent pid is valid
original_ppid = os.getppid()
if original_ppid != self.parent_pid:
self.parent_pid = 0
parent_exited = False
if self.parent_pid > 0:
try:
os.kill(self.parent_pid, 0)
except ProcessLookupError:
parent_exited = True
except PermissionError:
pass
# A live launcher may have started the kernel through a wrapper.
if not parent_exited:
self.parent_pid = 0

get_logger().debug(
"%s: poll for parent change with original parent pid=%d",
Expand Down
17 changes: 17 additions & 0 deletions tests/test_parentpoller.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,23 @@ def exit_mock(*args):
poller.run()


@pytest.mark.skipif(os.name == "nt", reason="only works on posix")
@pytest.mark.parametrize("parent_exists", [False, True])
def test_parent_poller_unix_parent_changed_before_start(parent_exists):
poller = ParentPollerUnix(parent_pid=221)
with (
mock.patch("os.getppid", side_effect=[220, 220, 1]),
mock.patch("os.kill", side_effect=None if parent_exists else ProcessLookupError) as kill,
mock.patch("os._exit", side_effect=SystemExit),
mock.patch("time.sleep") as sleep,
pytest.raises(SystemExit),
):
poller.run()

kill.assert_called_once_with(221, 0)
assert sleep.call_count == int(parent_exists)


@pytest.mark.skipif(os.name != "nt", reason="only works on windows")
def test_parent_poller_windows():
poller = ParentPollerWindows(interrupt_handle=1)
Expand Down
Loading