调用并产生守护进程来后台工作
2010-05-29 00:37
239 查看
程序如下:
守护进程.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<syslog.h>
//deamon function turn thr process who get it into a deamon progress
void deamon()
{
pid_t pid;
int fd;
pid=fork();
if(pid<0)
{
perror("fork error!");
return -1;
}
//first step:
if(pid!=0)
{
exit(0); //father progress exit,the child be a orphan progress
}
//second step: call setsid() to make a new session (对话)
pid=setsid();
if(pid==-1)
{
perror("setdid error!");
_exit(1);
}
// step third: change the work dir to "/"
chdir("/");
// step forth: close all the file disription,and STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO to /dev/null ;重新定向标准输出,标准输入,标准错误到/dev/null
fd=open("/dev/null",O_RDWR,0);
if(fd!=-1)
{
dup2(fd,STDIN_FILENO);
dup2(fd,STDOUT_FILENO);
dup2(fd,STDERR_FILENO);
if(fd>2)
{
close(fd);
}
}
else
{
perror("reDingXiang error!");
_exit(1);
}
//step fifth:set umask
umask(0027);
openlog("守护进程",LOG_CONS|LOG_PID,LOG_USER);
int count=0;
while(count<5)
{
syslog(LOG_INFO,"log info test。。。",count);
count++;
}
}
int main()
{
deamon();
sleep(1000);
return 0;
}
调用守护进程.c
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
main()
{
pid_t pid;
int status;
pid=vfork();
if(pid<0)
{
perror("fork error!/n");
}
else if(pid==0)
{
execlp("./守护进程","守护进程",NULL);
}
else
{
wait(&status);
while(1)
printf("father wait.../n");
}
}
执行
./调用守护进行
查看守护进程记录的内容
如果应用在服务器上,可以使用守护进程来监听端口,而主程序继续处理其它事物,在守护进程监听到端口又connect时候,可以记录下client的信息,最后主程序退出时候kill 守护进程即可,这样子也相当于fork()去处理一个连接事件,但可以后台处理,更加方便,实现真正的超级服务器设计
相关文章推荐
- 调用并产生守护进程来后台工作
- iPhone开发之—守护进程和前台进程之间的通信-前台应用发信息给后台的守护进程
- iphone守护进程和前台进程之间的通信-前台应用发信息给后台的守护进程
- Linux 后台进程与守护进程
- 工作记录--守护进程
- Nginx主进程切换为后台守护进程
- linux下创建后台守护进程实例
- 后台进程不等于守护进程
- Supervisor 管理后台守护进程
- 衔接UI线程和管理后台工作线程的类(多线程、异步调用)
- Openwrt(linux)启动服务后台进程守护进程
- iphone守护进程和前台进程之间的通信-前台应用发信息给后台的守护进程
- 2014-04-30工作日志:提取文件的路径及使用createprocess时,要用getmodulename获取要执行的模块的路径及调用createprocess时要记得关闭新建的进程
- 后台守护进程的创建
- 如何让你的App永远在后台存活:对Android进程守护、闹钟后台被杀死的研究
- Linux 后台守护进程
- Linux下后台守护进程的编写实例
- 用PHP实现守护进程任务后台运行与多线程(php-resque使用说明)
- 【正完成】守护进程让APP常驻后台
- linux下使用系统调用实现进程后台运行