bash 如何在不产生两个进程的情况下以不同的用户身份运行 nohup?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11727604/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I run nohup as a different user without spawning two processes?
提问by Apothem
I'm trying to nohup a command and run it as a different user, but every time I do this two processes are spawned.
我试图 nohup 一个命令并以不同的用户身份运行它,但每次我这样做时都会产生两个进程。
For example:
例如:
$ nohup su -s /bin/bash nobody -c "my_command" > outfile.txt &
This definitely runs my_command as nobody, but there's an extra process that I don't want to shown up:
这肯定会以nobody 身份运行my_command,但还有一个我不想显示的额外进程:
$ ps -Af
.
.
.
root ... su -s /bin/bash nobody my_command
nobody ... my_command
And if I kill the root process, the nobody process still lives... but is there a way to not run the root process at all? Since getting the id of my_command and killing it is a bit more complicated.
如果我杀死根进程,nobody 进程仍然存在……但是有没有办法根本不运行根进程?由于获取 my_command 的 id 并杀死它有点复杂。
回答by javdev
This could be achieved as:
这可以通过以下方式实现:
su nobody -c "nohup my_command >/dev/null 2>&1 &"
and to write the pid of 'my_command' in a pidFile:
并在 pidFile 中写入“my_command”的 pid:
pidFile=/var/run/myAppName.pid
touch $pidFile
chown nobody:nobody $pidFile
su nobody -c "nohup my_command >/dev/null 2>&1 & echo $! > '$pidFile'"
回答by user2196349
nohup runuser nobody -c "my_command my_command_args....." < /dev/null >> /tmp/mylogfile 2>&1 &
回答by Wangwang
If the user with nologin shell, run as follows:
如果用户使用 nologin shell,运行如下:
su - nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"
Or:
或者:
runuser - nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"
Or:
或者:
sudo su - nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"
sudo runuser -u nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"
回答by twalberg
You might do best to create a small script in e.g. /usr/local/bin/start_my_commandlike this:
您可能最/usr/local/bin/start_my_command好像这样创建一个小脚本:
#!/bin/bash
nohup my_command > outfile.txt &
Use chownand chmodto set it to be executable and owned by nobody, then just run su nobody -c /usr/local/bin/start_my_command.
使用chown和chmod将其设置为可执行并由 拥有nobody,然后运行su nobody -c /usr/local/bin/start_my_command。

