#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#define MAXFILE 65535 線程
void sigterm_handler(int arg) 進程
{ string
_running = 0; it
} io
int main() class
{ 終端
pid_t pc; 權限
int i, fd,len; grep
char* buf = 「My dameon\n」; 程序
len = strlen(buf);
pc = fork();//建立子線程
if(pc<0)
{
printf("error fork\n");
exit(1);
}
else if (pc >0)
exit(0);
//讓進城擺脫原會話的控制
//讓進程擺脫原進程組的控制
//讓進程擺脫原控制終端的控制
setsid();//
umask(0);//重置文件權限掩碼
for(i=0;i<MAXFILE;i++);
close(i);
signal(SIGTERM,sigterm_handler);
while(_running)
{
if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
{
perror("open");
exit(1);
}
write(fd,buf,len);
close(fd);
usleep(10*1000); //10毫秒
}
此程序每10毫秒將buf寫入文件
關閉時 用ps -ef|grep 得到進程號 而後 kill