2011-05-13 81 views
14

我有一個以前運行的進程(process1.sh)在後臺運行,其PID爲1111(或其他任意數字)。我怎麼能發送像command option1 option2那樣的PID到1111?發送命令到後臺進程

不要想要啓動一個新的process1.sh!

回答

12

命名管道是你的朋友。請參閱文章Linux Journal: Using Named Pipes (FIFOs) with Bash

+0

文章是偉大的,但我怎麼能發送「的東西somethingelse yetanotherthing」的過程?例如,我有一臺服務器運行,它接受「某事」,並對其進行處理。我怎麼能這樣做? – 2011-05-13 22:22:32

1

您無法將新參數發送到正在運行的進程。

但是,如果你正在實現這個過程或其過程,可以從一個管道採取參數,那麼其他答案將有所幫助。

+0

錯,您可以使用命名管道來處理這類事情。 – 2011-05-13 22:03:23

+0

@mu我這個問題讀取像用戶想要獲得新的參數(argc/argv在C中或位置參數在bash中)。一旦程序啓動,你不能給它新的參數。如果他是應用程序的作者,管道可以解決他的問題。他也可以實現一個TCP服務器......但是如果你正在談論一個現有的命令 - 那麼不會(如果他會說,我正在寫這個應用程序,我想運行在BG ...) – nhed 2011-05-13 22:08:24

+0

有在問題中有一些含糊不清的地方,但我沒有閱讀「發送類似命令option1 option2'」的意思,意思是在事後修改'argv',看起來Mohit只是想發送某種類型的消息給後臺shell腳本。 – 2011-05-13 22:33:54

1

基於答案:

  1. Writing to stdin of background process
  2. Accessing bash command line args [email protected] vs $*
  3. Why my named pipe input command line just hangs when it is called?
  4. Can I redirect output to a log file and background a process at the same time?

我寫了兩個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 

這第二個腳本,它只是一個包裝這讓我輕鬆發送命令到我的服務器:

發送。SH

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

half_life_pid_tail_file_name=my_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 "[email protected]" > /tmp/srv-input 
sleep 1 

exit 0 

現在每次我要發送到我的服務器命令我只是做終端:

./send.sh mp_timelimit 30 

該腳本可以讓我保持拖尾的過程中,您可將當前終端,因爲每次我發送一個命令時,它都會檢查是否有尾部進程在後臺運行。如果不是,它只是在每次過程發送輸出時啓動一次,我可以在我用來發送命令的終端上看到它,就像運行附加&運算符的應用程序一樣。


您可以隨時打開另一個打開的終端,只聽我的服務器服務器控制檯。要做到這一點只需使用tail命令與-f標誌跟隨我的服務器控制檯輸出:

./tail -f /home/user/Half-Life/my_logs.txt