Compile a simple Linux Service

Source: Internet
Author: User
Compile a simple Linux service-general Linux technology-Linux programming and kernel information. The following is a detailed description. Because some programs need to be transferred from windows to linux, but they are not familiar with linux, I asked my friends at the same time about how to write service programs in linux.

After learning about this, I will start writing the following:

First, write a program for service. The function is very simple. Write the current time to a file every one second:

Void recordTime ()
{
Const char pa [256] = "// home // projects // testService // recordTime ";
Ofstream fout;
Fout. open (pa, ios: app );
Time_t currTime;
Struct tm * tp;
Char buf [256];
While (1)
{
CurrTime = time (NULL );
Tp = localtime (& currTime );
Strftime (buf, 256, "% B % e, % Y, % H: % M: % S", tp );
Fout <"current time is" < Sleep (1 );
}
Fout. close ();
}

Then compile it into an executable file. I name it testService.

Then place a script file in/etc/init. d, which contains the function implementation of the Service Startup, shutdown, and restart:

Start ()
{
Echo "start testService"
/Home/projects/testService &
Exit 0;
}
Stop ()
{
Pkill testService
Echo "stop testService"
}

Case "$1" in
Start)
Start
;;
Stop)
Stop
;;
Restart)
Stop
Start
;;
*)
Echo "usage: $0 start | stop | restart"
Exit 0;
Esac

All functions are clear at a glance. Call the start () function to start the testService program in the background. stop () is used to stop the program. restart () simply executes the stop () and start () functions. When you need to start or stop the service, you only need to give the program a start/stop parameter.

In this way, this simple service is complete.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.