我有一个以前运行的进程(process1.sh),它在后台运行,PID为1111(或其他任意数字).我如何command option1 option2
使用1111的PID 发送类似于该过程的内容?
我并不想开始一个新的process1.sh!
基于以下答案:
我写了两个 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)