一、书写守护进程
步骤:
- 创建一个孤儿进程
- 创建一个新的会话组
- 修改运行目录到不可卸载的文件系统
- 重设文件权限掩码
- 关闭所有文件描述符
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
if(0 == fork())
{
//新建会话组
pid_t sid = setsid();
printf("sid = %d\n",sid);
//修改运行目录
chdir("/");
//清空文件权限掩码
umask(0);
//关闭所有文件描述符
for(int i=0;i<getdtablesize();i++)
close(i);
//书写功能代码
while(1)
{
printf("hello\n");
sleep(1);
}
}
return 0;
}
二、打印时钟在终端上,若终端输入quit,结束时钟
方法一:
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0)
{
time_t t;
struct tm *info=NULL;
while(1)
{
if(waitpid(-1,NULL,WNOHANG) > 0)
break;
t = time(NULL);
info = localtime(&t);
printf("%d-%02d-%02d %02d:%02d:%02d\r",info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
fflush(stdout);
sleep(1);
}
}
else if(0 == cpid)
{
char signal[10]="";
while(1)
{
scanf("%s",signal);
if(0 ==strcmp(signal,"quit"))
exit(0);
sleep(1);
}
}
return 0;
}
方法二:
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
//创建管道
int pipefd[2];
if(pipe(pipefd) < 0)
{
perror("pipe");
return -1;
}
char signal[10]="";
pid_t cpid = fork();
if(cpid > 0)
{
close(pipefd[0]); //关闭读端
sleep(1);
while(1)
{
scanf("%s",signal);
write(pipefd[1],signal,sizeof(signal));
if(0 == strcmp(signal,"quit"))
break;
}
wait(NULL);
}
else if(0 == cpid)
{
close(pipefd[1]); //关闭写端
int flag = fcntl(pipefd[0], F_GETFL); //获得原来的属性 flag
flag |= O_NONBLOCK; //修改flag
fcntl(pipefd[0], F_SETFL, flag);
time_t t;
struct tm *info=NULL;
char str[10];
while(1)
{
read(pipefd[0],signal,sizeof(signal));
if(0 == strcmp(signal,"quit"))
exit(0);
t = time(NULL);
info = localtime(&t);
printf("%d-%02d-%02d %02d:%02d:%02d\r",info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
fflush(stdout);
sleep(1);
}
}
return 0;
}