- 守护进程:
- 即后台运行的进程,随着系统的启动而启动,随着系统的终止而终止;
- 创建守护进程的流程:
- 一、创建孤儿进程(fork函数):
- 孤儿进程:
- 子进程没执行结束,父进程就已经退出,此时子进程就变成孤儿进程,不过孤儿进程会被
init进程回收; - 二、创建新的会话和新的进程组(setsid函数):
- setsid函数:
#include
#include
pid_t setsid(void);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 三、进程的工作目录切换到根目录(chdir函数):
- 可以不切换到根目录,只要保证此工作目录不被删除即可;
- chdir函数:
#include
int chdir(const char *path);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 四、设置所创建文件的掩码(umask函数):
- umask函数:
#include
#include
mode_t umask(mode_t mask);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 五、创建日志文件(open函数):
- 本示例代码采用的是当前的目录下创建日志文件;
int fd = open("./kkk.log",O_WRONLY|O_CREAT|O_TRUNC,0666);
- 六、进程的文件描述符(标准输入:0、标准输出:1、标准出错:2)重定向到文件中(dup2函数):
- dup2函数:
#include
int dup2(int oldfd, int newfd);
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char const *argv[])
{
pid_t pid = 0;
int fd = 0;
char buf[] = "I Love China!!!\n";
if(-1 == (pid = fork()))
{
perror("fork error");
exit(EXIT_FAILURE);
}else if(0 < pid){
exit(EXIT_SUCCESS);
}else if(0 == pid){
if(-1 == setsid())
{
perror("setsid error");
exit(EXIT_FAILURE);
}
umask(0);
if(-1 == (fd = open("./kkk.log",O_WRONLY|O_CREAT|O_TRUNC,0666)))
{
perror("open error");
exit(EXIT_FAILURE);
}
dup2(fd,0);
dup2(fd,1);
dup2(fd,2);
write(fd,buf,sizeof(buf));
}
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
linux@ubuntu:~$ gcc k1.c
linux@ubuntu:~$ ./a.out
linux@ubuntu:~$ cat kkk.log
I Love China!!!
linux@ubuntu:~$