孤儿进程
父进程先于子进程结束,此时子进程就是孤儿进程,孤儿进程被init进程收养
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, const char *argv[]) {
if (fork() == 0) {
while (1) {
sleep(1);
}
}
return 0;
}
此时查看a.out为孤儿进程, 且处于后台休眠态
unbuntu@ubuntu:~ $ ./a.out
unbuntu@ubuntu:~ $ ps -ajx | grep a.out
1 40722 40721 36846 pts/2 40772 S 1000 0:00 ./a.out
36846 40773 40772 36846 pts/2 40772 S+ 1000 0:00 grep --color=auto a.out
僵尸进程
子进程死掉之后,父进程没有为它回收资源,此时进程就是僵尸进程。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, const char *argv[]) {
if (fork() > 0) {
while (1) {
sleep(1);
}
}
return 0;
}
此时查看a.out为僵尸进程 (第一个为后台运行的父进程)
unbuntu@ubuntu:~ $ ./a.out &
[1] 41268
unbuntu@ubuntu:~ $ ps -ajx | grep a.out
36846 41268 41268 36846 pts/2 41281 S 1000 0:00 ./a.out
41268 41270 41268 36846 pts/2 41281 Z 1000 0:00 [a.out] <defunct>
36846 41282 41281 36846 pts/2 41281 S+ 1000 0:00 grep --color=auto a.out
守护进程
守护进程是后台运行的进程,脱离某个终端,随着系统的启动而运行,随着系统的终止而终止
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PRINT_ERR(msg) \
do { \
printf("%s:%s:%d\n", __FILE__, __func__, __LINE__); \
perror(msg); \
exit(-1); \
} while (0)
int main(int argc, const char *argv[]) {
int pid = fork();
if (pid < 0) {
return -1;
} else if (pid == 0) {
// 设置组id和会话id
if (setsid() == -1) {
PRINT_ERR("setsid error");
}
// 修改路径
if (chdir("/") == -1) {
PRINT_ERR("change dir error");
}
// 创建日志文件
int fd;
if ((fd = open("daemon.log", O_RDWR|O_CREAT|O_APPEND|O_TRUNC)) == -1) {
PRINT_ERR("open daemon.log error");
}
// 重定向标准输入输出错误到日志
dup2(fd, 0);
dup2(fd, 1);
dup2(fd, 2);
// 开启服务
while (1) {
printf("test dammon code....\n");
fflush(stdout);
sleep(1);
}
} else {
exit(0);
}
return 0;
}
运行后,查看 a.out 以及根目录下daemon.log 文件
此时a.out 被1号进程收养, 被设置为守护进程.
unbuntu@ubuntu:~ $ gcc daemon.c
unbuntu@ubuntu:~ $ sudo ./a.out
[sudo] password for unbuntu:
unbuntu@ubuntu:~ $ ps -ajx | grep a.out
1 41651 41651 41651 ? -1 Ss 0 0:00 ./a.out
36846 41702 41701 36846 pts/2 41701 S+ 1000 0:00 grep --color=auto a.out
unbuntu@ubuntu:~ $ sudo tail -f /daemon.log
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
test dammon code....
^C
unbuntu@ubuntu:~ $