【发布时间】:2011-08-25 06:47:30
【问题描述】:
我有一个以前运行的进程 (process1.sh),它在后台运行,PID 为 1111(或其他任意数字)。我怎样才能向 PID 为 1111 的进程发送 command option1 option2 之类的内容?
我不想开始一个新的 process1.sh!
【问题讨论】:
我有一个以前运行的进程 (process1.sh),它在后台运行,PID 为 1111(或其他任意数字)。我怎样才能向 PID 为 1111 的进程发送 command option1 option2 之类的内容?
我不想开始一个新的 process1.sh!
【问题讨论】:
命名管道是你的朋友。见文章Linux Journal: Using Named Pipes (FIFOs) with Bash。
【讨论】:
您不能将新参数发送到正在运行的进程。
但是,如果您正在实施此过程或其可以从管道中获取参数的过程,那么其他答案会有所帮助。
【讨论】:
argv,在我看来Mohit只是想发送向后台 shell 脚本发送某种消息。
如果您不想局限于信号,您的程序必须支持其中一种进程间通信方法。请参阅corresponding Wikipedia article。
一个简单的方法是让它监听Unix domain socket上的命令。
【讨论】:
有关如何通过命名管道 (fifo) 从 shell 向服务器发送命令,请参见此处:
Redirecting input of application (java) but still allowing stdin in BASH
How do I use exec 3>myfifo in a script, and not have echo foo>&3 close the pipe?
【讨论】:
您可以使用 bash 的 coproc comamnd。 (仅适用于 4.0+) - 就像 ksh 的 |&
【讨论】:
根据答案:
我编写了两个 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
第二个脚本只是一个包装器,让我可以轻松地将命令发送到我的服务器:
send.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
现在每次我想向我的服务器发送命令时,我都会在终端上执行:
./send.sh mp_timelimit 30
这个脚本允许我在你当前的终端上继续跟踪进程,因为每次我发送一个命令时,它都会检查是否有一个在后台运行的尾进程。如果没有,它只会启动一个,每次进程发送输出时,我都可以在我用来发送命令的终端上看到它,就像你运行的应用程序附加 & 运算符一样。
您可以随时打开另一个打开的终端来监听我的服务器服务器控制台。为此,只需使用带有-f 标志的tail 命令来跟踪我的服务器控制台输出:
./tail -f /home/user/Half-Life/my_logs.txt
【讨论】: