精灵进程简要说明(摘抄 冰狐)
正文:
1.daemon进程特点
a:以root运行
b:没有控制终端
c:是进程组和会话的首进程
d:父进程都是init
2.编程规则
(1)fork, 退出父进程exit
(2)调用setsid
(3)改当前工作目录为根目录 >>>防止,更改前的目录可能无法被动态卸载
(4)将文件方式创建屏蔽字设置为0
(5)关闭文件描述符
3实例:
初始化你的守护进程函数
init.c
#include
#include
#include
#include
#include
extern void init_daemon(void)
{
int pid = 0;
int i = 0;
if(pid=fork())
exit(0);
else if(pid< 0)
exit(1);
setsid();
if(pid=fork())
exit(0);
else if(pid< 0)
exit(1);
for(i=0;i< NOFILE;++i)
close(i);
chdir("/tmp");
umask(0);
return;
}
test.c
#include
#include
void init_daemon(void);
int main(int argc, char *argv[])
{
FILE *fp = NULL;
time_t t;
init_daemon();
while(1)
{
sleep(2);
fp = fopen("test.log", "a");
if(fp >= 0){
t = time(0);
fprintf(fp, "i am here\n", asctime(localtime(&t)));
fclose(fp);
}
}
return 0;
}
Makefile
#******--Makefile--*******
CC=gcc
CXX=g++
SOURCES = init.c test.c
OBJS = $(SOURCES:.c=.o)
LIB = -I/usr/include -I
all:test
.PHONY : all
test: $(OBJS)
@echo OBJS=$(OBJS)
$(CC) -o $@ $(OBJS)
.SUFFIXES:
.SUFFIXES: .c .cpp .o
.c.o:
$(CC) -c -o $@ $<
.cpp.o:
$(CXX) -c -o $@ $<
clean:
rm test $(OBJS)
4.操作
在当前命令行里输入make 就会调用Makefile 文件 自己编译。然后执行./test,你的守护进程就开始转起来了。用prstat 命令可以看到你的进程./test
打开目录tmp,用tail -f test.log 跟踪一下,就会发现你的进程每隔2秒就输出i'am here.
用kill pid 可以杀死你的进程./test。
ok...!
阅读(1317) | 评论(0) | 转发(0) |