用syslog记录调试信息+程序只能运行一次(实现)

今天有点懒
这个也比较简单
具体注意事项(自己写的时候发现的问题)都写在了注释

主要是要仔细看man手册

#include<stdio.h>
#include <syslog.h>

int main(void)
{
	//这里第一个参数可以是null,然后在syslog里面会显示你执行文件的名字
	//刚开始我直接写NULL,是可以的,后面试试想a.out,结果报错
	//后面发现呢要加上一个“a.out”,这样之后呢就会显示成是你要它显示的名字了。
	//第二个参数是一些option选项,一般是LOG_CONS,LOG_PID就显示pid出来
	openlog("进程信息",LOG_CONS|LOG_PID,LOG_USER);
	
	//第一个参数是一些level选项,跟信息的重要性有关的,之前一直找priority在哪里,其实优先级就是level了,所以看level才对。
	//第二个参数就是你要显示的信息了,可以直接“hello”,也支持像printf一样的格式,像上面这样写。
	char a[100] = "helloarrr";
	syslog(LOG_DEBUG,"%s",a);

	//ok之后就关掉就行。
	closelog();

	
	return 0;
}

程序只能运行一次(实现)

#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>


#define FILE "./1time"    


void delete_file(void);     //声明这个delete——file的函数

int main(void)
{
	//程序只能运行一次
	int fd = -1;
	fd = open(FILE, O_RDWR| O_CREAT|O_EXCL|O_TRUNC );
	// EEXIST : pathname already exists and O_CREAT and O_EXCL were used.
	// O_TRUNC :If the file already exists and is a regular file and the access mode allows writing (i.e.,O_RDWR or O_WRONLY) it will be truncated to length 0.

	if(fd < 0)
	{
		perror("open");
		if(EEXIST == errno) //用到error number 在perror里面找头文件
		{
			printf("this file has been open\n");
			return -1;
		}
	}
	
	atexit(delete_file);
	
	int i = 0;
	for(i=1;i<=5;i++)
	{
		printf("I am running...%d\n",i);
		sleep(1);
	}



	return 0;
}

void delete_file(void)
{
	remove(FILE); // remove函数可以这样直接删掉文件
}
发布了38 篇原创文章 · 获赞 1 · 访问量 1035

猜你喜欢

转载自blog.csdn.net/qq_40897531/article/details/104176786
今日推荐