Write Daemon under Linux

Source: Internet
Author: User

Under Linux (for example, Redhat Linux Enterprise Edition 5.3), it is sometimes necessary to write a service. Service is also a program, generally with the system initiates the user does not intervene to quit the program, can be called service. Service under Linux is generally called daemon.

The above is the definition of a generalized service. The service under Linux is generally placed under the/etc/init.d folder. Browse through the files in this folder to find out how the service is generally followed under Linux.

A common principle of writing service under Linux
1) A service that is actually running is typically placed in a bin directory (/BIN,/USR/BIN,ETC).
2) The/etc/init.d folder is typically a shell script used to control the service under the Bin directory.
3) shell scripts under the/ETC/INIT.D folder generally accept at least two parameters, start and stop. There are other commonly used optional parameters such as Status,reload,restart, etc.
4) The shell script under the/etc/init.d folder includes at least two lines of comments, one line tells Chkconfig that the service is running RunLevel, start priority, and end priority. A line tells Chkconfig the description of this service.

Two Linux boot process and RunLevel
To understand the Linux startup process and RunLevel, you can browse the/etc/inittab file first. The following 7 types of runlevel are defined in/etc/inittab. Each service can set its own runlevel under which to run. You can call/sbin/init <runlevel> enter the appropriate runlevel, such as running/sbin/init 6 will cause the system to restart. If a service fails to start under one of the RunLevel, causing the system to fail, you can disable or modify the service (a bit like Safe mode under Windows) by entering RunLevel that does not have this service configured.

# 0-halt (do not set Initdefault to this)
# 1-single User mode
# 2-multiuser, without NFS (the same as 3, if you don't have networking)
# 3-full Multiuser mode
# 4-unused
# 5-x11
# 6-reboot (do not set Initdefault to this)


The default runlevel is also defined under the/etc/inittab file. As below, represents the default RunLevel is 5.
Id:5:initdefault:

Under the/etc folder, execute ls-d rc*, which lists the following files and directories:
RC rc0.d rc1.d rc2.d rc3.d rc4.d rc5.d rc6.d rc.d rc.local rc.sysinit
RC is a script that, in/etc/inittab, executes RC <runlevel> according to RunLevel. The RC script will go to the appropriate RCN.D to execute the following script. Rc.local is the last called script that can put some user-defined tasks inside.

Entering the RCN.D folder, you will find links to scripts that begin with S and K, with 2 digits behind S and K. where s represents start,k on behalf of Kill. s script, which is called in RC with the start parameter, and the script starting with the K, with the stop parameter when called in RC. The 2 digits behind S and K represent the priority of the service, and the higher the number, the later the execution. Most of the links to these scripts are destined for the/etc/init.d folder.

Now everything is clear. We can control the start and end of the service at the start and exit of the system by creating a soft link to the/ETC/INIT.D script under the appropriate RCN.D folder by the established specification. However, it is inconvenient to create a soft link manually, Redhatlinux provides chkconfig to help create these soft links. As long as the service control scripts placed under/ETC/INIT.D conform to the Chkconfig conventions mentioned earlier (annotations Chkconfig and description), you can use Chkconfig--add <service> chkconfig --list <service> chkconfig--del <service> and other commands to control the service startup or not.

Three examples
1) Below is a service written in the C + + language, which generates a 4-bit random number every 5 seconds in the/tmp/random file. Compiled by g++-O myrand myrand.cpp. Then put the Myrand in the/root/bin/folder.

/* Myrand.cpp
* This program read 4 chars from/dev/random in each iteration,
* and then adjust it to 0-9. Finally the 4 chars is written
* To/tmp/random. This was only for Testing/dev/random, and
* At the same time serve as a example service.
*/
#include <iostream>
#include <fstream>
using namespace Std;
#include <unistd.h>

int main ()
{
while (true)
{
Ifstream ifile ("/dev/random");
Char ch;
Char str[5];
str[4]=0;
int i;
for (i=0;i<4;i++)
{
IFile >> ch;
if (ch<0) ch=-ch;
CH = ch% 10;
Ch= ' 0 ' + ch;
Str[i]=ch;
}


Ofstream ofile ("/tmp/random");
Ofile << str << Endl;
Sleep (5);
}
}

2) Below is a script, named Myrandservice, placed under the/etc/init.d folder:

#!/bin/sh
#
# chkconfig:2345 80 50
# Description:myrandservice is for testing how to write service in Linux
#
# Processname:myrandservice
#
# Source function library.
. /etc/rc.d/init.d/functions

Ret=0

Start () {
# Check FDB status
echo "Start Myrandservice"
Daemon/root/bin/myrand &
Ret=$?
}

Stop () {
echo "Stop Myrandservice"
Kill-9 $ (ps-ef | grep myrand | grep-v grep | awk ' {print $} ')
Ret=$?
}

Status () {
Local result
echo "Check Status of Myrandservice ..."
#lines =$ (ps-ef | grep myrand | grep-v grep | )
#echo $lines
result=$ (ps-ef | grep myrand | grep-v myrandservice | grep-v grep | wc-l)
#echo $result
If [$result-gt 0]; Then
echo "My randservice is up"
Ret=0
Else
echo "My randservice is down"
Ret=1
Fi
echo "Check status of Myrandservice...done."
}

# See how we were called.
Case "$" in
Start
Start
;;
Stop
Stop
;;
Status
Status
;;
*)
echo $ "Usage: $ {Start|stop|status}"
Exit 1
Esac

Exit $ret

3) Use/sbin/chkconfig--add Myrandservice to set the secondary daemon to start automatically. You can also see that the corresponding script link is created automatically under RC3.D,RC4.D,RC5.D.

4) Examples of some of the explanations
The following two lines of the script in the example are for chkconfig. 2345 for this service is on RunLevel 2, 3, 4, 5, 80 for the start priority, and 50 for the end priority. If no value is added to the runlevel, substituting "-" means that the service does not start automatically under any runlevel and needs to be started manually. Service can be controlled or queried through service <service-name> Start/stop/status.

# chkconfig:2345 80 50
# Description:myrandservice is for testing how to write service in Linux

The daemon function in the script exists in/etc/rc.d/init.d/functions. Daemon will redirect output to/dev/null and will also set whether to generate Coredump files. Programs that start with Daemon will ensure that the service runs without exiting, even if the user exits the command line shell. Other useful functions, such as Killproc,status, are also included in/etc/rc.d/init.d/functions to kill the service and view the status of the service.

Another realization of four Deamon

Without using daemon in/etc/rc.d/init.d/functions, the daemon program is designed to follow this procedure:

(1) Call fork after the program runs and let the parent process exit. The child process obtains a new process ID, but inherits the process group ID of the parent process.

(2) Call Setsid to create a new session, make itself a leader of the new session and the new process group, and make the process without a control terminal (TTY).

(3) Set the file creation mask to 0, avoid the effect of permission when the file is created.

(4) Close the unwanted open file descriptor. Because the daemon program executes in the background and does not need to interact with the terminal, it usually shuts down stdin, stdout, and stderr. Other according to the actual situation treatment.

(5) Daemon cannot output information and can use syslog or its own log system for log processing. (optional)

(6) Write a shell script to manage daemon, and use service to manage and monitor daemon. (optional)

Reference:

Http://www.cnblogs.com/khler/archive/2011/01/30/1947971.html

Write Daemon under Linux

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.