Linux後台運行,linux後台
在Linux中有時你需要將指令碼(test.sh)和可執行程式(exe)後台執行,請使用如下方式:
nohup ./test.sh &
nohup ./exe &
這樣執行的程式可以徹底在後台運行,為什麼呢?因為如果你的指令碼或者可執行程式中有echo,cout這種向標準輸出裝置輸送內容的指令,普通的後台運行:
./test.sh &
./exe &
是無法滿足要求的,當指令往標準輸出裝置輸出,而當前shell視窗正好被關閉之後,指令就 找不到標準輸出裝置,程式就會退出。這當然不是你要的後台運行。但是加上nohup後,nohup會在目前的目錄建立nohup.out文字檔,當有內容需要傳輸到標準輸出裝置時就會重新導向到此文字檔,程式就可以真正的後台運行了。
下面的指令碼和C++代碼可以測試上面的觀點:
shell指令碼test.sh
#!/bin/bashwhile((1))do echo "Hello" sleep 1done
C++ 代碼:每隔一秒鐘向標準輸出列印一行內容
#include <iostream> #include "ace/Log_Msg.h" #include "ace/Event_Handler.h" #include "ace/Reactor.h" using namespace std; #include "ace/Thread_Manager.h" class My_Timer_Handler : public ACE_Event_Handler { public: My_Timer_Handler(const int delay,const int interval); ~My_Timer_Handler(); virtual int handle_timeout (const ACE_Time_Value ¤t_time, const void *); private: int i; long id; }; My_Timer_Handler::My_Timer_Handler(const int delay,const int interval):i(0) { this->reactor(ACE_Reactor::instance()); id=this->reactor()->schedule_timer(this, 0, ACE_Time_Value(delay), ACE_Time_Value(interval)); } My_Timer_Handler::~My_Timer_Handler() { cout<<"~My_Timer_Handler()"<<endl; } bool stop_event_loop = false; int My_Timer_Handler::handle_timeout (const ACE_Time_Value ¤t_time, const void *act = 0){ cout<<"hello handle_timeout"<<++i<<endl; } int main(int, char *[]) { My_Timer_Handler temp_timer(0,1); while(true) { ACE_Reactor::instance()->handle_events(); } };
linux 怎後台運行
一般情況下關閉終端時,那麼在這個終端中啟動的背景程式也會終止,要使終端關閉後,背景程式保持執行,使用這個指令:
nohup test.sh &
linux中怎把一個進程放在後台運行
nohup /usr/local/php_fcgi/bin/php /home/ftp/1520/a/scripts/collect/run.php &記得輸出重新導向