linux 后台进程

守护进程

1 定义

守护进程是脱离于终端并且在后台运行的进程.

2 创建守护进程步骤

1)创建子进程,父进程退出.

2)在子进程中创建新会话.(最重要的一步,使用系统函数setsid)

3)改变当前目录为根目录

4)重设文件权限掩码

5)关闭文件描述符

调用setsid有三个作用:

1)让进程摆脱原会话的控制

2)让进程摆脱原进程组的控制

3)让进程摆脱原控制终端的控制

示例程序如下:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

#include <fcntl.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <sys/stat.h>

#define MAXFILE 65535

int main()

{

pid_t pc;

int i, fd, len;

char *buf = "this is a Daemon\n";

len = strlen(buf);

pc = fork(); // first

if(pc < 0)

{

printf("error fork\n");

exit(1);

}

else if(pc > 0)

{

exit(0);

}

setsid(); // second

chdir("/"); // third

umask(0); // fourth

for(i=0; i<MAXFILE; i++) // five

close(i);

while(1)

{

if((fd = open("/tmp/daemon.log", O_CREAT | O_WRONLY | O_APPEND, 0600)) < 0)

{

perror("open");

exit(1);

}

write(fd, buf, len+1);

close(fd);

sleep(10);

}

return 0;

}