What is the equivalent of 'nohup' in linux PowerShell?

*爱你&永不变心* 提交于 2021-01-01 06:40:42

问题


I very well know existence of duplicate question. But that question is marked answered and I don't think it at all answers the original question.

The $ nohup command keeps executing command even if the parent process (shell) of nohup dies. More info here: What's the difference between nohup and ampersand.

In case of Win32 api, I see line When the system is terminating a process, it does not terminate any child processes that the process has created. Terminating a process does not generate notifications for WH_CBT hook procedures.. This is the desired behaviour I am asking about. This works with win32 powershell automatically. But with linux powershell's Start-Job it's merely background job in the powershell context in the sense that it gets killed when powershell gets killed.

Example:

➜  ~ powershell-preview -c "Start-Job { /bin/sleep 1000 }"

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Running       True            localhost             /bin/sleep 1000

➜  ~ ps ux  | grep sleep
mvaidya   166986  0.0  0.0   9032   664 pts/11   S+   18:59   0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn --exclude-dir=.idea --exclude-dir=.tox sleep

回答1:


Using Start-Job or PowerShell v6+'s & background operator isn't an option, because terminating the job will also terminate child processes launched from it, which jobs are - both on Windows and on Unix-like platforms.

However, you can achieve nohup-like behavior via the Start-Process cmdlet:

On Unix-like platforms, you can combine Start-Process with nohup:
The following example launches a background PowerShell instance that stays alive even after you close the launching terminal; it emits a . every second, and nohup collects both stdout and stderr output in file nohup.out in the current directory, appending to such a file if it already exists:

# Runs for 2 minutes and appends both stdout and stderr output to ./nohup.out
Start-Process nohup 'pwsh -nop -c "1..120 | % { write-host . -nonewline; sleep 1 }"'

On Windows, where Start-Process by default creates an independent process in a new console window, you can use -WindowStyle Hidden to launch that process in a hidden window that will remain alive independently of the launching shell.

# Runs for 2 minutes and appends success output to ./nohup.out
Start-Process -WindowStyle Hidden pwsh '-nop -c "1..120 | % { Add-Content -nonewline nohup.out -Value .; sleep 1 }"'


来源:https://stackoverflow.com/questions/64707869/what-is-the-equivalent-of-nohup-in-linux-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!