Bash:使用其他用户获取进程的pid [英] Bash: Get pid of a process using a different user

查看:138
本文介绍了Bash:使用其他用户获取进程的pid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash中有一个脚本来启动Java程序,我想在执行后获取程序的pid。 pid将保存在文本文件中。

I have a script in bash to start a java program and I want to get the pid of the program after it executes. The pid will be saved in a text file.

现在,我有这样的内容:

Right now I have something like this:

if [ "$USER" == "root" ]
then
    su $APP_USER -c "nohup java $JAVA_OPTS  >> $LOG_OUT 2>> $LOG_ERR &"
    su $APP_USER -c "echo $! > $PID_PATH/$CAT.pid"
else
    nohup java $JAVA_OPTS >> $LOG_OUT 2>> $LOG_ERR &
    echo $! > "$PID_PATH/$CAT.pid"
fi

我也尝试过这样做,但是

I also tried like this but it doesn't work neither.

if [ "$USER" == "root" ]
then
    su $APP_USER -c "(nohup java $JAVA_OPTS  >> $LOG_OUT 2>> $LOG_ERR &); (echo $! > $PID_PATH/$CAT.pid)"
else
    nohup java $JAVA_OPTS >> $LOG_OUT 2>> $LOG_ERR &
    echo $! > "$PID_PATH/$CAT.pid"
fi

当我以APP_USER身份运行时,当我以root用户身份运行时,我的java程序启动但pid文件创建为空,效果很好。

when I run as my APP_USER all works great, when I run as root my java program starts but the pid file is created empty.

推荐答案

尝试

su $APP_USER -c "nohup java $JAVA_OPTS  >> $LOG_OUT 2>> $LOG_ERR & echo \$! > $PID_PATH/$CAT.pid"

\ $!后面的$ c>可以防止变量扩展,然后再传递给su命令。

\ behind $! prevents expansion of the variable, before passing to the su command.

这篇关于Bash:使用其他用户获取进程的pid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆