Linux C启动时创建pid文件
程序在启动时将pid写入文件,当程序再次启动时会进行检测,避免启动多个实例。
util-pidfile.h文件
#ifndef __UTIL_PID_H__
#define __UTIL_PID_H__ int PidfileCreate(const char *);
void PidfileRemove(const char *);
int PidfileTestRunning(const char *pid_filename); #endif /* __UTIL_PID_H__ */
util-pidfile.c文件
#include <stdio.h>
#include <inttypes.h> // PRIuMAX
#include <errno.h> // errno
#include <string.h> // strerror #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> // getpid
#include <signal.h> // kill #include "util-debug.h"
#include "util-pidfile.h" /**
* \brief Write a pid file (used at the startup)
* This commonly needed by the init scripts
*
* \param pointer to the name of the pid file to write (optarg)
*
* \retval 0 if succes
* \retval -1 on failure
*/
int PidfileCreate(const char *pidfile)
{
int pidfd = ;
char val[]; int len = snprintf(val, sizeof(val), "%"PRIuMAX"\n", (uintmax_t)getpid());
if (len <= ) {
LogError("Pid error (%s)", strerror(errno));
return(-);
} pidfd = open(pidfile, O_CREAT | O_TRUNC | O_NOFOLLOW | O_WRONLY, );
if (pidfd < ) {
LogError("unable to set pidfile '%s': %s",
pidfile,
strerror(errno));
return(-);
} ssize_t r = write(pidfd, val, (unsigned int)len);
if (r == -) {
LogError("unable to write pidfile: %s", strerror(errno));
close(pidfd);
return(-);
} else if ((size_t)r != len) {
LogError("unable to write pidfile: wrote"
" %"PRIdMAX" of %"PRIuMAX" bytes.", (intmax_t)r, (uintmax_t)len);
close(pidfd);
return(-);
} close(pidfd);
return();
} /**
* \brief Remove the pid file (used at the startup)
*
* \param pointer to the name of the pid file to write (optarg)
*/
void PidfileRemove(const char *pid_filename)
{
if (pid_filename != NULL) {
/* we ignore the result, the user may have removed the file already. */
(void)unlink(pid_filename);
}
} /**
* \brief Check a pid file (used at the startup)
* This commonly needed by the init scripts
*
* \param pointer to the name of the pid file to write (optarg)
*
* \retval 0 if succes
* \retval -1 on failure
*/
int PidfileTestRunning(const char *pid_filename)
{
if (access(pid_filename, F_OK) == ) {
/* Check if the existing process is still alive. */
pid_t pidv;
FILE *pf; pf = fopen(pid_filename, "r");
if (pf == NULL) {
LogError("pid file '%s' exists and can not be read. Aborting!",
pid_filename);
return -;
} if (fscanf(pf, "%d", &pidv) == && kill(pidv, ) == ) {
fclose(pf);
LogError("pid file '%s' exists. Is program already running? Aborting!",
pid_filename);
return -;
} fclose(pf);
}
return ;
}
util-debug.h日志打印(主要是为了方便以后使用其他打印接口,就不用再修改util-pidfile.c文件了)
#ifndef __UTIL_DEBUG_H__
#define __UTIL_DEBUG_H__ #ifndef LOG_PRINT
#define LOG_MAX_LOG_MSG_LEN 2048
#define Log(x, file, func, line, ...) \
do { \
char _log_msg[LOG_MAX_LOG_MSG_LEN]; \
snprintf(_log_msg, LOG_MAX_LOG_MSG_LEN, __VA_ARGS__); \
fprintf(stdout, "<%s> %s\n", x, _log_msg); \
} while() #define LogError(...) Log("ERROR", \
__FILE__, __FUNCTION__, __LINE__, __VA_ARGS__) #define LogWarning(...) Log("WARNING", \
__FILE__, __FUNCTION__, __LINE__, __VA_ARGS__) #define LogInfo(...) Log("INFO", \
__FILE__, __FUNCTION__, __LINE__, __VA_ARGS__) #define LogDebug(...) Log("DEBUG", \
__FILE__, __FUNCTION__, __LINE__, __VA_ARGS__) #define FatalError(...) do { \
LogError(__VA_ARGS__); \
exit(EXIT_FAILURE); \
} while()
#endif #endif //__UTIL_DEBUG_H__
main.c文件
#include <stdio.h>
#include <unistd.h> #include "util-pidfile.h" int main()
{
int result = ; const char *pidfile = "/var/run/test_pid01.pid"; if (PidfileTestRunning(pidfile) != )
return -; PidfileCreate(pidfile); while (){
sleep();
} PidfileRemove(pidfile);
return ;
}
编译完成后运行该程序,然后再启动一个终端,再次运行这个程序的时候就会打印程序已运行并退出。
<ERROR> pid file '/var/run/test_pid01.pid' exists. Is program already running? Aborting!
Linux C启动时创建pid文件的更多相关文章
- ARM linux内核启动时几个关键地址【转】
转自:http://www.cnblogs.com/armlinux/archive/2011/11/06/2396787.html 1. 内核启动地址1.1. 名词解释ZTEXTAD ...
- Linux开机启动时执行脚本的方法
方法 1 – 使用 rc.local利用 /etc/ 中的 rc.local 文件在启动时执行脚本与命令.我们在文件中加上一行来执行脚本,这样每次启动系统时,都会执行该脚本.不过我们首先需要为 /et ...
- linux 在启动时获得专用的缓冲
如果你真的需要一个大的物理上连续的缓冲, 最好的方法是在启动时请求内存来分配它. 在启动时分配是获得连续内存页而避开 get_free_pages 施加的对缓冲大小限制的唯一 方法, 不但最大允许大小 ...
- 在tomcat启动时解析xml文件,获取特定标签的属性值,并将属性值设置到静态变量里
这里以解析hibernate.cfg.xml数据库配置信息为例,运用dom4j的解析方式来解析xml文件. 1.在javaWeb工程里新建一个java类,命名为GetXmlValue.java,为xm ...
- Servlet --启动时创建、配置url、ServlectContext、初始化参数、获取资源
servlet的版本的区别 2.5版本, Servlet的配置只支持在xml文件中的配置 3.0版本: Servlet的配置支持在xml文件中的配置, 也可以使用注解的方式, 默认使用注解 让服务器在 ...
- linux下fallocate快速创建大文件
以前创建文件我一般用dd来创建,例如创建一个512M的文件: dd命令可以轻易实现创建指定大小的文件,如 dd if=/dev/zero of=test bs=1M count=1000 会生成一个1 ...
- Linux基础命令---htpasswd创建密码文件
htpasswd htpasswd指令用来创建和更新用于基本认证的用户认证密码文件.htpasswd指令必须对密码文件有读写权限,否则会返回错误码. 此命令的适用范围:RedHat.RHEL.Ubun ...
- linux下使用vim创建编辑文件
vi/vim 使用实例 如果要想用vim/vi创建一个文件(使用命令): vim test.txt 不管文件存在与否 直接输入 vi 文件名 就能够进入 vi 的一般模式 按下 i 进入输入模式( ...
- mysql启动失败:不能创建pid文件
2016-03-09T07:51:38.905444Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/ ...
随机推荐
- [Abp vNext 源码分析] - 3. 依赖注入与拦截器
一.简要说明 ABP vNext 框架在使用依赖注入服务的时候,是直接使用的微软提供的 Microsoft.Extensions.DependencyInjection 包.这里与原来的 ABP 框架 ...
- 【朝花夕拾】Android安全之(一)权限篇
前言 从Android6.0开始,Android系统对权限的处理产生了很大的变化.如果APP运行的设备系统版本为Android6.0或更高,并且target在23或更高,那么danger ...
- springboot~Compiler时开启插件的注解功能
对于IJ这个IDE工具来说,我们会安装一些插件来帮助我们更好的进行开发,像lombok就是一款不错的插件,使用注解的方式在项目编译时帮助我们生成代码,像getter,setter,tostring等等 ...
- MySQL优化小建议
背景 "那啥,你过来一下!" "怎么了?我代码都单元测试了的,没出问题啊!"我一脸懵逼跑到运维大佬旁边. "你看看!你看看!多少条报警,赶快优化一下! ...
- 【大数据安全】Apache Kylin 安全配置(Kerberos)
1. 概述 本文首先会简单介绍Kylin的安装配置,然后介绍启用Kerberos的CDH集群中如何部署及使用Kylin. Apache Kylin™是一个开源的分布式分析引擎,提供Hadoop/Spa ...
- Java基础系列-Comparable和Comparator
原创文章,转载请标注出处:<Java基础系列-Comparable和Comparator> 一.概述 Java中的排序是由Comparable和Comparator这两个接 ...
- 推荐三个 VSCode 摸鱼插件
周三是一周中最难以度过的一天,离上个周末过去了两天,离下个周末也还有两天.为了让各位更好地搬(mo)砖(yu),今天给大家推荐三款效(mo)率(yu)工(shen)具(qi)! 一.听歌插件 1 功能 ...
- JavaScript小记二则:接上一节:用.net写Textbox控件关于数字的判断的另一则方法
方法二.通过写JS进行判断控制输入的只能为数字,源码如下: <!DOCTYPE html> <html> <body> <h1></h1> ...
- 【转载】Sqlserver日期时间格式化总结
在Sqlserver数据库中,允许存储datetime的时间类型,该存储类型包含时间的时分秒以及毫秒等数值,在SQL语句查询的时候,很多时候我们需要对查询出来的日期数据进行格式化操作,Sqlserve ...
- python 面试题
1.os.path与sys.path的区别是什么? os.path 主要用于系统文件路径的操作 sys.path 主要是python解释器的系统环境参数的操作 2.re模块中match和search方 ...