René's URL Explorer Experiment


Title: In multiple threads applications, using fork results in occasional blocking rather than occasional hanging up. · Issue #111635 · python/cpython · GitHub

Open Graph Title: In multiple threads applications, using fork results in occasional blocking rather than occasional hanging up. · Issue #111635 · python/cpython

X Title: In multiple threads applications, using fork results in occasional blocking rather than occasional hanging up. · Issue #111635 · python/cpython

Description: Bug report Bug description: In multi-threaded applications, using fork results in blocking rather than hanging up. We have a multi-threaded application, and in order to interact with scripts, we use a self-developed component similar to ...

Open Graph Description: Bug report Bug description: In multi-threaded applications, using fork results in blocking rather than hanging up. We have a multi-threaded application, and in order to interact with scripts, we us...

X Description: Bug report Bug description: In multi-threaded applications, using fork results in blocking rather than hanging up. We have a multi-threaded application, and in order to interact with scripts, we us...

Opengraph URL: https://github.com/python/cpython/issues/111635

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"In multiple threads applications, using fork results in occasional blocking rather than occasional hanging up.","articleBody":"# Bug report\n\n### Bug description:\n\n# In multi-threaded applications, using fork results in blocking rather than hanging up.\n\nWe have a multi-threaded application, and in order to interact with scripts, we use a self-developed component similar to  [[pexpect](https://github.com/pexpect/pexpect)](https://github.com/pexpect/pexpect).  issue: https://github.com/pexpect/ptyprocess/issues/50, https://github.com/pexpect/pexpect/issues/369. The underlying implementation uses os.fork(). According to related issues, this can occasionally lead to unexpected deadlocks, as discussed in https://discuss.python.org/t/concerns-regarding-deprecation-of-fork-with-alive-threads/33555. However, our scenario is quite interesting. In our case, the child process gets blocked, and it doesn’t return until after a timeout of 30 seconds. Additionally, this slowness manifests suddenly and persistently from a black box perspective. Normally, it should take less than 0.1 seconds, but in problematic environments, it can persist for more than 20 seconds, and even up to 30 seconds, eventually causing the child process to be killed due to a timeout. Alternatively, the process may execve to a root process, becoming unkillable and turning into a zombie process. The code and phenomena are as follows:\n\nCode:\n\nInitializing an expect instance for command execution:\n\n~~~python\ndef build(self, command, first_require=\"Username:\",\n                   second_require=\"Password:\", timeout=72000):\n    self.logger.info('get cmd: %s', command)\n    process = expect.Spawn(command)\n    try:\n        idx = process.expect([first_require], 30)\n        if idx == 0:\n            process.send_line(self.adm_user)\n        else:\n            self.logger.error(\"excute zenithctl output: %s\" % process.child_process_output)\n            self.error_message = process.child_process_output\n            self.close(process)\n            return False\n        ```\n        return False\n    except Exception:\n        self.logger.info(traceback.format_exc())\n        self.logger.info(\"run command failed\")\n        return False\n    finally:\n        self.close(process)\n~~~\n\nExpect implementation, the main tasks performed by the child process include: Setting the window size, setting echo, closing file descriptors, and executing execve.\n\n```python\ndef _do_spawn(self):\n        if not self.execute_file:\n            raise ExpectException('Execute file is not selected')\n\n        try:\n            child_pid, child_fd = pty.fork()\n        except OSError:\n            raise ExpectException('Execute pty fork failed.')\n\n        if child_pid == pty.CHILD:\n            try:\n                # Set window size\n                try:\n                    set_win_size_method = getattr(termios, 'TIOCSWINSZ', -2146929561)\n                    windows_size = struct.pack('HHHH', 1920, 1080, 0, 0)\n                    fcntl.ioctl(sys.stdin.fileno(), set_win_size_method, windows_size)\n                except IOError as io_error:\n                    if io_error.args[0] not in (errno.EINVAL, errno.ENOTTY):\n                        raise ExpectException('Set window size exception')\n\n                # Set echo\n                try:\n                    attr = termios.tcgetattr(sys.stdin.fileno())\n                    attr[3] = attr[3] & ~termios.ECHO\n                    termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, attr)\n                except termios.error as termi_err:\n                    if termi_err.args[0] == errno.EINVAL:\n                        raise IOError(termi_err.args[0], '%s: Set echo failed.' % termi_err.args[1])\n                    raise ExpectException('Set echo failed.')\n                except IOError as io_error:\n                    if io_error.args[0] == errno.EINVAL:\n                        raise IOError(io_error.args[0], '%s: Set echo failed.' % io_error.args[1])\n                    raise ExpectException('Set echo failed.')\n\n                # Close unnecessary open files\n                max_file_no = resource.getrlimit(resource.RLIMIT_NOFILE)[0]\n                os.closerange(3, max_file_no)\n                signal.signal(signal.SIGHUP, signal.SIG_IGN)\n\n                # Execute command line\n                os.execv(self.execute_file, self.execute_command_args)\n            except BaseException:\n                # Exit child process in case of any exception\n                sys.exit(1)\n        else:\n            # Handle parent process if needed\n            self._process_parent_process(child_pid, child_fd)\n```\n\nThe `process.expect([first_require], 30)` method utilizes selectors and epoll for implementation, waiting for the child process to produce output.\n\n\n\nThe `close` function in `expect`.\n\n```python\ndef close(self):\n        if self.is_child_process_closed:\n            return\n        \n        os.close(self.child_fd)\n        if self.sel:\n            self.sel.close()\n\n        time.sleep(self.close_child_process_delay)\n        while True:\n            # Check if the child process is still alive\n            if self.child_process_terminated:\n                break\n            waitpid_options = 0 if self.child_process_read_eof else os.WNOHANG\n            try:\n                process_id, process_status = os.waitpid(self.child_pid, waitpid_options)\n                if process_id == 0:\n                    continue\n                if os.WIFEXITED(process_status):\n                    self.child_process_status = os.WEXITSTATUS(process_status)\n                elif os.WIFSIGNALED(process_status):\n                    self.child_process_status = os.WTERMSIG(process_status)\n                elif os.WIFSTOPPED(process_status):\n                    raise ExpectException('Process already been stopped.')\n                self.child_process_terminated = True\n                break\n            except OSError as e:\n                if e.errno == errno.ECHILD:\n                    raise ExpectException('Process already not exist.')\n                else:\n                    raise\n            break\n\n        if not self.child_process_terminated:\n            # Try to terminate the child process\n            kill_signals = [signal.SIGHUP, signal.SIGCONT, signal.SIGINT, signal.SIGKILL]\n            for _signal in kill_signals:\n                try:\n                    os.kill(self.child_pid, _signal)\n                except OSError as e:\n                    if e.errno != errno.ESRCH:\n                        time.sleep(self.terminate_child_process_delay)\n                        continue\n                break\n\n        self._set_closed_status()\n```\n\n\n\ncommand is :\n\n```shell\n/usr/bin/sudo -u xxx /bin/bash -c \"xxx\"\n```\n\nPhenomenon:\n\n- The logs for the exception branch \"execute zenithctl output:\" and the entrance log \"get cmd:\" are just over 30 seconds apart.\n- In the failure scenario, there is no record in the sudo logs.\n- Calling build twice in a ten-second interval, but seeing the output in the sudo logs within the same second. Additionally, the call time and the time recorded in the sudo logs are all over 10 seconds, even reaching 20 or 30 seconds.\n- In the sudo logs, some entries have TTY=unknown while others have TTY=pts/0.\n- The script that was supposed to be executed did not run.\n- The issue occurred in multiple live environments without any obvious pattern and couldn't be reproduced by us.\n- Retrying in the failing environment still results in failure.\n- Adjusting the execution time period still leads to failure.\n- Manually executing the command is very fast.\n- In the problematic scenario, system resources are normal, not exceptionally high.\n- Zombie processes appeared because, after 30 seconds, when we tried to kill the process, we found that the sudo process had already been started and the user did not have the permissions to handle it.\n- After restarting the service, the problem disappeared.\n- The first time the service was deployed, the file descriptor limit was 65536, and after restarting, it was 4096.\n\nProgress:\n\nWe are almost certain that the child process is blocked, not deadlocked; it's just slow, not perpetually stuck. The specific location is from after the fork in the child process to before the execve is finally executed. It’s unclear exactly where it is getting blocked. We have ruled out all system calls that could potentially block.\n\nPoints of confusion:\n\nUsing fork in a multithreading environment cannot explain why when calling build twice at a ten-second interval, the output appears in the sudo logs within the same second. Moreover, both the call time and the time recorded in the sudo logs exceed 10 seconds, sometimes even reaching 20 or 30 seconds.\n\nSuspicions:\n\nThe process is blocked after fork, waiting for some resources, and these resources are eventually acquired. What's puzzling is what unusual scenario triggers this situation.\n\n### CPython versions tested on:\n\n3.9\n\n### Operating systems tested on:\n\nLinux","author":{"url":"https://github.com/113xiaoji","@type":"Person","name":"113xiaoji"},"datePublished":"2023-11-02T08:19:41Z","url":"https://github.com/python/cpython/issues/111635"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:b261c5ed-f405-e2eb-05d5-29bbb02d992e
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id88EE:14700E:421AEF2:53D8845:6B0222E8
html-safe-noncefaf125270912bebd2a12e67fe3cd72914bd1b91583f0c252544683fdfdbab28d
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4OEVFOjE0NzAwRTo0MjFBRUYyOjUzRDg4NDU6NkIwMjIyRTgiLCJ2aXNpdG9yX2lkIjoiNTgxODQxNTc2ODQ2NzAyMjU2OCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac882da1f95fe5bb35d69e3f10107673559df3f0b78d8b9e08deb41e54532df8f1
hovercard-subject-tagissue:1973734161
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/111635/issue_layout
twitter:imagehttps://opengraph.githubassets.com/14aa3b898dde9af8af882f46a031ef9aa46cd5cd32b5fb228725c99e84769236/python/cpython/issues/111635
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/14aa3b898dde9af8af882f46a031ef9aa46cd5cd32b5fb228725c99e84769236/python/cpython/issues/111635
og:image:altBug report Bug description: In multi-threaded applications, using fork results in blocking rather than hanging up. We have a multi-threaded application, and in order to interact with scripts, we us...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:username113xiaoji
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/111635#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F111635
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F111635
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/111635
Reloadhttps://github.com/python/cpython/issues/111635
Reloadhttps://github.com/python/cpython/issues/111635
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/111635
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/111635
In multiple threads applications, using fork results in occasional blocking rather than occasional hanging up.https://github.com/python/cpython/issues/111635#top
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/113xiaoji
113xiaojihttps://github.com/113xiaoji
on Nov 2, 2023https://github.com/python/cpython/issues/111635#issue-1973734161
pexpecthttps://github.com/pexpect/pexpect
https://github.com/pexpect/pexpecthttps://github.com/pexpect/pexpect
pexpect/ptyprocess#50https://github.com/pexpect/ptyprocess/issues/50
pexpect/pexpect#369https://github.com/pexpect/pexpect/issues/369
https://discuss.python.org/t/concerns-regarding-deprecation-of-fork-with-alive-threads/33555https://discuss.python.org/t/concerns-regarding-deprecation-of-fork-with-alive-threads/33555
113xiaojihttps://github.com/113xiaoji
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
on Nov 2, 2023https://github.com/python/cpython/issues/111635#event-10840707891
https://github.com/113xiaoji
113xiaojihttps://github.com/113xiaoji
on Nov 2, 2023https://github.com/python/cpython/issues/111635#issuecomment-1790266985
@itamarsthttps://github.com/itamarst
@gpsheadhttps://github.com/gpshead
113xiaojihttps://github.com/113xiaoji
on Nov 2, 2023https://github.com/python/cpython/issues/111635#event-10841008095
113xiaojihttps://github.com/113xiaoji
on Nov 2, 2023https://github.com/python/cpython/issues/111635#event-10841105965
https://github.com/gpshead
gpsheadhttps://github.com/gpshead
on Nov 3, 2023https://github.com/python/cpython/issues/111635#issuecomment-1791777099
gpsheadhttps://github.com/gpshead
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Nov 3, 2023https://github.com/python/cpython/issues/111635#event-10850631291
https://github.com/113xiaoji
113xiaojihttps://github.com/113xiaoji
on Nov 3, 2023https://github.com/python/cpython/issues/111635#issuecomment-1791823198
@gpsheadhttps://github.com/gpshead
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/111635
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/111635
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.