为使用 nohup 启动的进程提供自定义名称

问题描述 投票:0回答:2

当我使用

exec
创建新流程时,我可以使用
-a
选项给它一些自定义名称,即
exec -a MyName MyCommand

这样做可以处理一堆以不同参数启动的相同进程。例如,如果我有以下内容:

exec -a MyName1 MyCommand param1
exec -a MyName2 MyCommand param2

出于某种原因我想杀死后者它很简单:

pkill -f MyName2
.

问题是我不知道如何使用

nohup
开始的进程达到相同的效果。我读过
-p
选项,但并不总是支持它。
disjoin
似乎也不起作用。

有人遇到过类似的问题吗?

bash shell
2个回答
4
投票

Bash 的

exec
命令为此有一个
-a NAME
选项:

nohup bash -c 'exec -a xxx sleep 12345'

根据

help exec

exec: exec [-cl] [-a name] [command [argument ...]] [redirection ...]
    Replace the shell with the given command.

    Execute COMMAND, replacing this shell with the specified program.
    ARGUMENTS become the arguments to COMMAND.  If COMMAND is not specified,
    any redirections take effect in the current shell.

    Options:
      -a name   pass NAME as the zeroth argument to COMMAND
      -c        execute COMMAND with an empty environment
      -l        place a dash in the zeroth argument to COMMAND

    If the command cannot be executed, a non-interactive shell exits, unless
    the shell option `execfail' is set.

    Exit Status:
    Returns success unless COMMAND is not found or a redirection error occurs.

0
投票

首先你不需要

nohup
;它不做 shell 自己做不到的事情。

exec -a MyName1 MyCommand param1 >nohup.out 2>&1 </dev/null & disown -h "$!"
exec -a MyName2 MyCommand param2 >nohup.out 2>&1 </dev/null & disown -h "$!"

nohup 所做的大部分只是重定向。其余部分与

disown -h
相同(它告诉 shell 不要将 HUP 信号转发给该进程)。

当然,您也可以选择一个不同的文件来存储每个命令的日志,并将 PID 存储在变量中 - 执行后者将使您根本不需要使用

pgrep

© www.soinside.com 2019 - 2024. All rights reserved.