Daemon

时间 : 14-09-09 栏目 : 操作系统 作者 : noway 评论 : 0 点击 : 438 次

Daemon程序是一直运行的服务端程序,又称为守护进程。通常在系统后台运行,没有控制终端不与前台交互,Daemon程序一般作为系统服务使用。Daemon是长时间运行的进程,通常在系统启动后就运行,在系统关闭时才结束。一般说Daemon程序在后台运行,是因为它没有控制终端,无法和前台的用户交互。Daemon程序一般都作为服务程序使用,等待客户端程序与它通信。我们也把运行的Daemon程序称作守护进程

 

Daemon程序实现方法编辑

编写Daemon程序有一些基本的规则,以避免不必要的麻烦。
1、首先是程序运行后调用fork,并让父进程退出。子进程获得一个新的进程ID,但继承了父进程进程组ID。
2、调用setsid创建一个新的session,使自己成为新session和新进程组的leader,并使进程没有控制终端(tty)。
3、改变当前工作目录至根目录,以免影响可加载文件系统。或者也可以改变到某些特定的目录。
4、设置文件创建mask为0,避免创建文件时权限的影响。
5、关闭不需要的打开文件描述符。因为Daemon程序在后台执行,不需要于终端交互,通常就关闭STDIN、STDOUT和STDERR。其它根据实际情况处理。
另一个问题是Daemon程序不能和终端交互,也就无法使用printf方法输出信息了。我们可以使用syslog机制来实现信息的输出,方便程序的调试。在使用syslog前需要首先启动syslogd程序,关于syslogd程序的使用请参考它的man page,或相关文档,我们就不在这里讨论了。

Daemon程序实现例子编辑

一个Daemon程序的例子 编译运行环境为Redhat Linux 8.0。
我们新建一个daemontest.c程序,文件内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<stdio.h>
#include<syslog.h>
#include<signal.h>
intdaemon_init(void)
{
    pid_tpid;
    if((pid=fork())<0)return(-1);
    elseif(pid!=0)exit(0);/*parentexit*/
    /*childcontinues*/
    setsid();/*becomesessionleader*/
    chdir("/");/*changeworkingdirectory*/
    umask(0);/*clearfilemodecreationmask*/
    close(0);/*closestdin*/
    close(1);/*closestdout*/
    close(2);/*closestderr*/
    return(0);
}
voidsig_term(intsigno)
{
    if(signo==SIGTERM)
        /*catchedsignalsentbykill(1)command*/
    {
        syslog(LOG_INFO,"programterminated.");
        closelog();
        exit(0);
    }
}
intmain(void)
{
    if(daemon_init()==-1)
    {
        printf("can'tforkself\n");
        exit(0);
    }
    openlog("daemontest",LOG_PID,LOG_USER);
    syslog(LOG_INFO,"programstarted.");
    signal(SIGTERM,sig_term);/*arrangetocatchthesignal*/
    while(1)
    {
        sleep(1);/*putyourmainprogramhere*/
    }
    return(0);
}
使用如下命令编译该程序: gcc -Wall -o daemontest daemontest.c编译完成后生成名为daemontest的程序,执行./daemontest来测试程序的运行。
使用ps axj命令可以显示系统中已运行的daemon程序的信息,包括进程ID、session ID、控制终端等内容。
部分显示内容:
PPID PID PGID SID TTY TPGID STAT UID TIME COMMAND
1098 1101 1101 1074 pts/1 1101 S 0 0:00 -bash 1 1581 777 777 ? -1 S 500 0:13 gedit 1 1650 1650 1650 ? -1 S 500 0:00 ./daemontest 794 1654 1654 794 pts/0 1654 R 500 0:00
ps axj 从中可以看到daemontest程序运行的进程号为1650。
我们再来看看/var/log/messages文件中的信息: Apr 7 22:00:32 localhost
daemontest[1650]: program started.
我们再使用kill 1650命令来杀死这个进程,/var/log/messages文件中就会有如下的信息:
Apr 7 22:11:10 localhost daemontest[1650]: program terminated.
使用ps axj命令检查,发现系统中daemontest进程已经没有了。
词条标签:

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog-old.z3a105.com/?p=101

Daemon:等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群


0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!

KUBET