将命令发送到后台进程

Moh*_*nde 17 bash process

我有一个以前运行的进程(process1.sh),它在后台运行,PID为1111(或其他任意数字).我如何command option1 option2使用1111的PID 发送类似于该过程的内容?

并不想开始一个新的process1.sh!

hak*_*ick 13

命名管道是你的朋友.请参阅文章Linux Journal:使用命名管道(FIFO)和Bash.


use*_*ser 5

基于以下答案:

  1. 写入后台进程的标准输入
  2. 访问 bash 命令行参数 $@ 与 $*
  3. 为什么我的命名管道输入命令行在调用时挂起?
  4. 我可以同时将输出重定向到日志文件和后台进程吗?

我写了两个 shell 脚本来与我的游戏服务器通信。


第一个脚本在计算机启动时运行。它确实启动了服务器并将其配置为在后台运行时读取/接收我的命令:

start_czero_server.sh

#!/bin/sh

# Go to the game server application folder where the game application `hlds_run` is
cd /home/user/Half-Life

# Set up a pipe named `/tmp/srv-input`
rm /tmp/srv-input
mkfifo /tmp/srv-input

# To avoid your server to receive a EOF. At least one process must have
# the fifo opened in writing so your server does not receive a EOF.
cat > /tmp/srv-input &

# The PID of this command is saved in the /tmp/srv-input-cat-pid file
# for latter kill.
# 
# To send a EOF to your server, you need to kill the `cat > /tmp/srv-input` process
# which PID has been saved in the `/tmp/srv-input-cat-pid file`.
echo $! > /tmp/srv-input-cat-pid

# Start the server reading from the pipe named `/tmp/srv-input`
# And also output all its console to the file `/home/user/Half-Life/my_logs.txt`
#
# Replace the `./hlds_run -console -game czero +port 27015` by your application command
./hlds_run -console -game czero +port 27015 > my_logs.txt 2>&1 < /tmp/srv-input &

# Successful execution 
exit 0
Run Code Online (Sandbox Code Playgroud)

这第二个脚本只是一个包装器,它允许我轻松地将命令发送到我的服务器:

发送.sh

half_life_folder="/home/jack/Steam/steamapps/common/Half-Life"

half_life_pid_tail_file_name=hlds_logs_tail_pid.txt
half_life_pid_tail="$(cat $half_life_folder/$half_life_pid_tail_file_name)"

if ps -p $half_life_pid_tail > /dev/null
then
    echo "$half_life_pid_tail is running"
else   
    echo "Starting the tailing..."
    tail -2f $half_life_folder/my_logs.txt &
    echo $! > $half_life_folder/$half_life_pid_tail_file_name
fi

echo "$@" > /tmp/srv-input
sleep 1

exit 0
Run Code Online (Sandbox Code Playgroud)

现在每次我想向我的服务器发送命令时,我只需在终端上执行:

./send.sh mp_timelimit 30
Run Code Online (Sandbox Code Playgroud)

这个脚本允许我在你当前的终端上继续跟踪进程,因为每次我发送一个命令时,它都会检查是否有一个尾进程在后台运行。如果没有,它只是启动一个,每次进程发送输出时,我都可以在我用来发送命令的终端上看到它,就像你运行的应用程序附加&操作符一样。


你总是可以打开另一个打开的终端,只是为了收听我的服务器控制台。要做到这一点,只需使用tail带有-f标志的命令来跟随我的服务器控制台输出:

./tail -f /home/user/Half-Life/my_logs.txt
Run Code Online (Sandbox Code Playgroud)