打印时钟在终端上,输入quit,结束时钟

一、书写守护进程

步骤:

  1. 创建一个孤儿进程
  2. 创建一个新的会话组
  3. 修改运行目录到不可卸载的文件系统
  4. 重设文件权限掩码
  5. 关闭所有文件描述符
#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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值