linux进程阻塞例子,一个Linux守候进程例子

其他程序可以调用void daemon_init(const char * cmd)方法,来初始化当前进程为守候进程

#include

#include

#include

#include

#include

#include

void daemon_init(const char * cmd);

int main(int argc, char * argv[])

{

daemon_init("liyachao_d");

time_t ticks;

while(1)

{

sleep(60);

ticks = time(NULL);

syslog(LOG_INFO,"%s",asctime(localtime(&ticks)));

}

return 0;

}

void daemon_init(const char * cmd)

{

int i;

int fd0;

int fd1;

int fd2;

pid_t pid;

struct rlimit rl;

struct sigaction sa;

/*清空文件默认生成权限*/

umask(0);

/*取得最大的文件描述符*/

if(getrlimit(RLIMIT_NOFILE,&rl) < 0 )

{

printf("can't get file limit.");

}

pid = fork();

if(pid < 0 )

{

printf("fork error.");

exit(1);

}

else if(pid > 0)

{

exit(0);

}

setsid();

/*

Ensure future opens won't allocate controlling TTYs.

*/

sa.sa_handler =SIG_IGN;

sigemptyset(&sa.sa_mask);

sa.sa_flags = 0;

if(sigaction(SIGHUP,&sa,NULL) < 0 )

{

printf("catn't ignore SIGHUP");

exit(1);

}

pid = fork();

if(pid < 0 )

{

printf("child fork error.");

exit(1);

}

else if(pid > 0)

{

exit(0);

}

/*改变工作目录到root*/

if(chdir("/") < 0 )

{

printf("can't change directory to /");

exit(1);

}

/*关闭所有的文件描述符*/

if (rl.rlim_max == RLIM_INFINITY)

{

rl.rlim_max = 1024;

}

for (i = 0; i < rl.rlim_max; i++)

{

close(i);

}

/*重定向文件描述符0,1,2,到/dev/null*/

fd0 = open("/dev/null",O_RDWR);

fd1 = open("/dev/null",O_RDONLY);

fd2 = open("/dev/null",O_RDWR);

openlog(cmd, LOG_CONS, LOG_DAEMON);

/*初始化日志文件*/

if (fd0 != 0 || fd1 != 1 || fd2 != 2)

{

syslog(LOG_ERR, "unexpected file descriptors %d %d %d",fd0, fd1, fd2);

exit(1);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值