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/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();  
    }  
};  

相关内容