Linux应用小题
创建一个文件,向文件中每隔1s记录一次日期和时间,并且按照顺序向后递增,例如:
然后呢,该记录可以暂停,可以继续,然后还可以退出;如果下次再次启动,继续在上次退出时的后面继续排序写入记录。
#include<stdio.h>
#include<time.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
#include<signal.h>
int g_stop=0; //1:暂停记录时间,0:开始或继续记录时间
int g_return=0; //退出记录时间
#define OK 0
#define ERROR -1
int g_count=-1; //从0开始排序记录
FILE *g_fp=NULL;
#define SPACE 32 //空格键控制时间记录
#define Q 113 //q键退出记录
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
void *timecount(void *arg){
time_t t;
struct tm *mytm=NULL; //获取时间信息的结构体
while(1)
{
pthread_mutex_lock(&g_mutex);
if(g_return){
pthread_mutex_unlock(&g_mutex);
break;
pthread_mutex_lock(&g_mutex);
}
pthread_mutex_unlock(&g_mutex);
pthread_mutex_lock(&g_mutex);
if(g_stop){
pthread_mutex_unlock(&g_mutex);
sleep(1);
continue;
pthread_mutex_lock(&g_mutex);
}
pthread_mutex_unlock(&g_mutex);
t=time(NULL);
mytm=localtime(&t);
fprintf(g_fp,"%d %d-%d-%d %d:%d:%d\n",++g_count,mytm->tm_year+1900,mytm->tm_mon+1,
mytm->tm_mday,mytm->tm_hour,mytm->tm_min,mytm->tm_sec);
fflush(g_fp); //刷新缓冲区,写入到文件中
sleep(1);
}
}
void *getstopsignal(void *arg){
int ch;
while(1){
ch=fgetc(stdin); //从终端命令行接收输入
switch(ch){
case SPACE:
if(!g_stop){
pthread_mutex_lock(&g_mutex);
puts("send stop");
g_stop=1;
pthread_mutex_unlock(&g_mutex);
}else{
pthread_mutex_lock(&g_mutex);
puts("send continue");
g_stop=0;
pthread_mutex_unlock(&g_mutex);
}
break;
case Q:
pthread_mutex_lock(&g_mutex);
puts("send return");
g_return=1;
pthread_mutex_unlock(&g_mutex);
break;
default:break;
}
if(g_return){break;}
sleep(1);
}
}
int main(void){
pthread_t tid_1;
pthread_t tid_2;
int ret;
g_fp=fopen("time.txt","a+"); //创建文件
if(NULL==g_fp){
puts("open or create file fail");
return ERROR;
}
char ch;
while((ch=fgetc(g_fp))!=EOF){
//如果已有记录就从文件的结尾继续递增记录
if(ch=='\n'){
g_count++;
}
}
//创建记录时间的线程
ret=pthread_create(&tid_1,NULL,timecount,NULL);
if(OK!=ret){
puts("create thread1 time count fail");
return ERROR;
}
//创建控制时间记录的线程
ret=pthread_create(&tid_2,NULL,getstopsignal,NULL);
if(OK!=ret){
puts("create thread2 signal get fail");
return ERROR;
}
//退出应用程序
while(1){
if(g_return){break;}
sleep(1);
}
//关闭文件
fclose(g_fp);
return OK;
}
看看执行的结果如何?