孤儿进程被init领养,无害。
僵尸进程占用pcb,没有被父进程的wait或者是waitpid回收,有害。
上面两个概念我比较熟悉。
Linux守护进程是一类在后台运行的特殊进程,用于执行特定的系统任务。很多守护进程在系统引导的时候启动,并且一直运行直到系统关闭。另一些只在需要的时候才启动,完成任务后就自动结束。
下面这段程序每隔6秒钟就向hello.log中写入一段数据……我们可以使用./test &让程序一直在后台运行,但是一旦关闭当前终端,进程就不会继续运行下去,所以这并不是一个在没有终端的情况下也能运行的守护进程……
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
void main()
{
FILE *fp;
time_t t;
while(1)
{
sleep(6);
fp=fopen("hello.log","a");
if(fp>=0)
{
time(&t);
fprintf(fp,"current time is:%s\n",asctime(localtime(&t)));
fclose(fp);
}
}
return;
}
改造一下上面的程序……让它成为守护进程……
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid<0)
exit(1);
else if(pid>0)
exit(0);
setsid();
pid=fork();
if(pid>0)
exit(0); /
else if(pid<0)
exit(1);
for(i=0;i<NOFILE;i++)
close(i);
chdir("/tmp");
umask(0);
return;
}
void main()
{
FILE *fp;
time_t t;
printf("pid = %d\n", getpid());
init_daemon();
while(1)
{
sleep(6);
fp=fopen("hello2.log","a");
if(fp>=0)
{
time(&t);
fprintf(fp,"current time is:%s\n",asctime(localtime(&t)));
fclose(fp);
}
}
return;
}改造之后的结果,启动程序之后会一直的在后台运行,即使终端关闭……
hello2.log是在/tmp文件夹下……
1、守护进程是一个孤儿进程,它的父进程是init;2、守护进程与任何终端无关。

京公网安备 11010502036488号