守护进程
代码:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <IOhead.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
static pid_t xd ;
if(cpid == 0)
{ pid_t sid=setsid();
printf("sid=%d\n",sid);
chdir("/");
umask(0);
for(int i =0;i<getdtablesize();i++)
close(i);
while(1)
sleep(1);
}
return 0;
}
运行结果:
打印时钟在终端上,若终端输入quit,结束时钟。
代码:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <IOhead.h>
int main(int argc, const char *argv[])
{
time_t t;
struct tm *p=NULL;
pid_t cpid = fork();
if(cpid > 0)
{ while(1)
{ t=time(NULL);
p=localtime(&t);
printf("%d-%02d-%02d-%02d-%02d-%02d\r",p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
fflush(stdout);
if(waitpid(cpid,NULL,WNOHANG)==cpid)
exit(0);
}
}
else if(cpid == 0)
{ while(1)
{ char s[128]="";
scanf("%s",s);
if(strcmp("quit",s)==0)
{
exit(0);
}
}
// kill(cpid,SIGTERM);
}
return 0;
}
运行结果:
思维导图: