红联Linux门户
Linux帮助

Linux下后台守护进程的编写实例

发布时间:2006-03-29 11:16:53来源:红联作者:[Hl.y]
相信随着Linux的普及,大家都在写不少Linux下的程序了,尤其是一些服务端程序慢慢地都转到Linux下了吧。大家必然碰到问题是如何让自己的进程成为守护进程,在系统启动的时候运行,并且永远是后台进程。下面就写一个这样的程序了。源代码如下:
//////////////////////////////init_daemon.c 开始///////////////////////////////////////////
#include
#include
#include
#include
#include

/*********************************************************************
*filename: init_daemon.c
*purpose: 产生后台进程
*wrote by: zhoulifa(zhoulifa@163.com) 周立发(http://zhoulifa.bokee.com)
*date time:2006-03-10 01:00:00
*Thanks to: 北京工业大学 小胡(本文摘自http://www.qtcn.org/bbs/simple/index.php?t116.html)
*Note: 任何人可以任意复制代码并运用这些代码,当然包括你的商业用途
* 但请遵循GPL
*********************************************************************/

void init_daemon(void)
{
int pid;
int i;

if(pid=fork())
exit(0);//是父进程,结束父进程
else if(pid< 0)
exit(1);//fork失败,退出

//是第一子进程,后台继续执行
setsid();//第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if(pid=fork())
exit(0);//是第一子进程,结束第一子进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长

for(i=0;i< NOFILE;++i)//关闭打开的文件描述符
close(i);
chdir("/tmp");//改变工作目录到/tmp
umask(0);//重设文件创建掩模
return;
}
//////////////////////////////init_daemon.c 结束///////////////////////////////////////////

上面这是个通用的函数,可以让你的程序成为后台守护进程。
下面是一个测试程序:
//////////////////////////////daemontest.c 开始///////////////////////////////////////////
#include
#include

/*********************************************************************
*filename: daemontest.c
*purpose: 测试后台进程
*wrote by: zhoulifa(zhoulifa@163.com) 周立发(http://zhoulifa.bokee.com)
*date time:2006-03-10 01:09:00
*Thanks to: 北京工业大学 小胡(本文参考了其文章http://www.qtcn.org/bbs/simple/index.php?t116.html)
*Note: 任何人可以任意复制代码并运用这些代码,当然包括你的商业用途
* 但请遵循GPL
*********************************************************************/

void init_daemon(void);//守护进程初始化函数
void signal_reload(int signal)
{
/*当收到SIGUSR1信号时程序重新导入所有参数*/
FILE *fp;
time_t t;
if((fp=fopen("test.log","a")) >=0)
{
t=time(0);
fprintf(fp,"I received signal(%d), reload all parameters at %s\n", signal, asctime(localtime(&t)) );
fclose(fp);
}
/*重新导入参数*/
}

void signal_handle(int signal)
{
/*当收到SIGUSR2信号时程序退出*/
FILE *fp;
time_t t;
if((fp=fopen("test.log","a")) >=0)
{
t=time(0);
fprintf(fp,"I received signal(%d), exit at %s\n", signal, asctime(localtime(&t)) );
fclose(fp);
}
exit(0);
}

int main(int argc, char ** argv)
{
FILE *fp;
time_t t;
init_daemon();//初始化为Daemon

signal(SIGCHLD, SIG_IGN);/*忽略子进程退出信号,若在此之后又产生了子进程,
如果不处理此信号,将在子进程退出后产生僵尸进程*/
signal(SIGUSR1, signal_reload);/*处理SIGUSR1信号,可以定义此信号为重导参数信号*/
signal(SIGUSR2, signal_handle);/*处理SIGUSR2信号,可以定义此信号为退出信号*/
while(1)//每隔一分钟向test.log报告运行状态
{
/*这是各位程序的主体部分,所以的工作在下面完成,比如http服务、FTP服务等*/
sleep(60);//睡眠一分钟
if((fp=fopen("test.log","a")) >=0)/*注意,由于在init_daemon里面已经把路径切换到了/tmp,因此此文件是/tmp/test.log*/
{
t=time(0);
fprintf(fp,"I'm here at %s\n",asctime(localtime(&t)) );
fclose(fp);
}
}
}
//////////////////////////////daemontest.c 结束///////////////////////////////////////////
编译时使用命令进行联合编译:
gcc init_daemon.c daemontest.c
产生了一个程序比如叫a.out

你就可以运行此程序了./a.out了。

如果想要此程序在系统启动时自动运行,你可以在/etc/rc.d/rc.local里面用su命令加上一行,比如:
su - Jacky -c "/bin/a.out"
这个命令将以Jacky用户身份运行/bin/a.out程序

程序运行过程中如果你修改了程序的参数,则必然希望程序重新导入参数,那么你可以用ps命令查看程序的进程号:
ps -ef|grep a.out
然后用kill命令向程序发参数,比如:
kill -s SIGUSR1 11422

同理,如果想要终止程序,则向程序发SIGUSR2信号:
kill -s SIGUSR2 11422
文章评论

共有 80 条评论

  1. 69.147.76.* 于 2007-09-05 12:46:50发表:

    http://emeraldring.fora.pl/
    http://emeraldring.fora.pl/
    http://emeraldring.fora.pl/ - emerald cut wedding ring

  2. 68.180.195.* 于 2007-09-02 06:23:23发表:

    Hi, nice very nice page..!
    fund raising cook book
    cookie dough fund raiser
    fund raising cook book
    fund raising counselor organization
    alaska permanent fund dividend

    Good luck !
    PS: do you listen Linkin Park ?

  3. 194.71.244.* 于 2007-08-31 21:03:14发表:

    Hi, nice very nice page..!
    fund raising counselor organization - http://fund.freewebpages.org/alaska-permanent-fund-dividend/index.html
    abb fund
    fund raising counselor organization - http://fund.freewebpages.org/fund-raising-cook-book/index.html
    fund - http://fund.freewebpages.org/mutual-fund-company/index.html
    fund

    Good luck !
    PS: do you listen Linkin Park ?

  4. 68.180.195.* 于 2007-08-29 08:57:00发表:

    Hi, nice very nice page..!
    money market account
    money banking and financial market - http://volny.cz/capitalmoney/high-yield-money-market-account/
    [URL=]capital money market[/URL]
    capital money market
    ford money market

    Good luck !
    PS: do you listen Linkin Park ?

  5. 67.155.176.* 于 2007-08-27 18:46:50发表:

    Hi, nice very nice page..!
    money market funds - http://volny.cz/highestmoney/high-yield-money-market/
    money market account
    cnn money market stock
    highest money market rate - http://www.volny.cz/moneymarket1/money-market-savings-account/
    ford money market

    Good luck !
    PS: do you listen Linkin Park ?

  6. 62.81.226.* 于 2007-08-25 21:53:57发表:

    Hi, nice very nice page..!
    money market rate
    vanguard money market funds - http://www.volny.cz/moneymarket1/money-market/
    cnn money market stock
    high yield money market
    ford money market account - http://www.volny.cz/moneymarket/money-market-interest-rate

    Good luck !
    PS: do you listen Linkin Park ?

  7. 210.51.51.* 于 2007-08-14 13:06:37发表:

    good work !
    chandelier lamp shades
    chandelier lamp shades
    chandelier lamp shades - www.desklamp1.fora.pl


    buy viagra online
    buy viagra online
    buy viagra online - www.buyviagraonlinex.fora.pl

    .
    norwegian pearl
    norwegian pearl
    norwegian pearl - http://volny.cz/norwegianpearl
    blackberry pearl white
    blackberry pearl white
    blackberry pearl white - http://volny.cz/blackberrypearlwhite
    pink pearls
    pink pearls
    pink pearls - http://volny.cz/pinkpearls
    blackberry pearl review
    blackberry pearl review
    blackberry pearl review - http://volny.cz/blackberrypearlrev
    pearl white
    pearl white
    pearl white - http://volny.cz/pearlwhite
    good luck

  8. 203.134.7.* 于 2007-08-14 13:06:16发表:

    good work !
    chandelier lamp shades
    chandelier lamp shades
    chandelier lamp shades - www.desklamp1.fora.pl


    buy viagra online
    buy viagra online
    buy viagra online - www.buyviagraonlinex.fora.pl

    .
    norwegian pearl
    norwegian pearl
    norwegian pearl - http://volny.cz/norwegianpearl
    blackberry pearl white
    blackberry pearl white
    blackberry pearl white - http://volny.cz/blackberrypearlwhite
    pink pearls
    pink pearls
    pink pearls - http://volny.cz/pinkpearls
    blackberry pearl review
    blackberry pearl review
    blackberry pearl review - http://volny.cz/blackberrypearlrev
    pearl white
    pearl white
    pearl white - http://volny.cz/pearlwhite
    good luck

  9. 81.169.173.* 于 2007-08-09 16:17:51发表:

    Hi, nice very nice page..!
    356 porsche sale 356 porsche sale 356 porsche sale - www.volny.cz/porsche356
    buy a pearl necklacebuy a pearl necklace buy a pearl necklace - http://volny.cz/buypearlnecklace
    porsche 928 porsche 928 porsche 928 - www.volny.cz/porsche928
    buy a pearl necklacebuy a pearl necklace buy a pearl necklace - http://volny.cz/buypearlnecklace
    944 porsche 944 porsche 944 porsche - www.volny.cz/porsche944

    Good luck !
    PS: do you listen Linkin Park ?

  10. 59.93.202.* 于 2007-08-07 17:42:29发表:

    desk lamp
    desk lamp - www.halogendesklamp.freehostia.com/desk-lamp/

    lamp shades
    lamp shades - www.halogendesklamp.freehostia.com/lamp-shades/

    office desk lamp
    office desk lamp - www.halogendesklamp.freehostia.com/office-desk-lamp/

  11. 85.114.16.* 于 2007-08-07 17:42:17发表:

    desk lamp
    desk lamp - www.halogendesklamp.freehostia.com/desk-lamp/

    lamp shades
    lamp shades - www.halogendesklamp.freehostia.com/lamp-shades/

    office desk lamp
    office desk lamp - www.halogendesklamp.freehostia.com/office-desk-lamp/

  12. 69.119.89.* 于 2007-08-05 16:29:44发表:

    nice site... look on my site

    http://www.desklamp.fora.pl - desk lamp
    http://www.lampshades.fora.pl - lamp shades

  13. 62.231.243.* 于 2007-08-02 11:40:35发表:

    diesel ford truck used
    diesel ford truck used
    diesel ford truck used - http://www.bcars.fora.pl/

    car insurance quote
    car insurance quote
    car insurance quote - http://www.carinsurancequote.fora.pl/

  14. 217.141.109.* 于 2007-08-02 08:27:24发表:

    extreme sex comics drawing planet http://cartoonfox.150m.com/extreme_sex_comics_drawing_planet.html extreme sex comics drawing planet extreme sex comics drawing planet

    bdsm extreme comic http://cartoonfox.150m.com/bdsm_extreme_comic.html bdsm extreme comic bdsm extreme comic

    bdsm extreme drawings http://cartoonfox.150m.com/bdsm_extreme_drawings.html bdsm extreme drawings bdsm extreme drawings

    art of bondage http://cartoonfox.150m.com/art_of_bondage.html art of bondage art of bondage

    extreme bondage cartoons http://cartoonfox.150m.com/extreme_bondage_cartoons.html extreme bondage cartoons extreme bondage cartoons

  15. 202.56.7.* 于 2007-07-31 18:35:23发表:

    gmc trucks here www.gmctruck.fora.pl
    gmc from america www.gmctruck.fora.pl
    real gmc www.gmctruck.fora.pl


    and www.emeraldring.fora.pl rings

  16. 125.229.72.* 于 2007-07-17 15:43:21发表:

    http://40430b76feaf4b14a89fbffcf4ada27e-t.xkktxb.org 40430b76feaf4b14a89fbffcf4ada27e http://40430b76feaf4b14a89fbffcf4ada27e-b1.xkktxb.org 40430b76feaf4b14a89fbffcf4ada27e http://40430b76feaf4b14a89fbffcf4ada27e-b3.xkktxb.org 8d1f2bfe3cbc5359328d95464cab8b7c

  17. 68.178.39.* 于 2007-07-09 11:24:56发表:

    adult comics rape comics