在Linux中有时你须要将脚本(test.sh)和可运行程序(exe)后台运行,请使用例如以下方式:
nohup ./test.sh &
nohup ./exe &
这样执行的程序能够彻底在后台执行,为什么呢?由于假设你的脚本或者可执行程序中有echo。cout这样的向标准输出设备输送内容的指令,普通的后台执行:
./test.sh &
./exe &
是无法满足要求的,当指令往标准输出设备输出。而当前shell窗体正好被关闭之后,指令就 找不到标准输出设备,程序就会退出。这当然不是你要的后台执行。
可是加上nohup后,nohup会在当前文件夹创建nohup.out文本文件。当有内容须要传输到标准输出设备时就会重定向到此文本文件,程序就能够真正的后台执行了。
以下的脚本和C++代码能够測试上面的观点:
shell脚本test.sh
#!/bin/bash
while((1))
do
echo "Hello"
sleep 1
done
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();
}
};