程序在启动时将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文件的更多相关文章

  1. ARM linux内核启动时几个关键地址【转】

    转自:http://www.cnblogs.com/armlinux/archive/2011/11/06/2396787.html 1.       内核启动地址1.1.   名词解释ZTEXTAD ...

  2. Linux开机启动时执行脚本的方法

    方法 1 – 使用 rc.local利用 /etc/ 中的 rc.local 文件在启动时执行脚本与命令.我们在文件中加上一行来执行脚本,这样每次启动系统时,都会执行该脚本.不过我们首先需要为 /et ...

  3. linux 在启动时获得专用的缓冲

    如果你真的需要一个大的物理上连续的缓冲, 最好的方法是在启动时请求内存来分配它. 在启动时分配是获得连续内存页而避开 get_free_pages 施加的对缓冲大小限制的唯一 方法, 不但最大允许大小 ...

  4. 在tomcat启动时解析xml文件,获取特定标签的属性值,并将属性值设置到静态变量里

    这里以解析hibernate.cfg.xml数据库配置信息为例,运用dom4j的解析方式来解析xml文件. 1.在javaWeb工程里新建一个java类,命名为GetXmlValue.java,为xm ...

  5. Servlet --启动时创建、配置url、ServlectContext、初始化参数、获取资源

    servlet的版本的区别 2.5版本, Servlet的配置只支持在xml文件中的配置 3.0版本: Servlet的配置支持在xml文件中的配置, 也可以使用注解的方式, 默认使用注解 让服务器在 ...

  6. linux下fallocate快速创建大文件

    以前创建文件我一般用dd来创建,例如创建一个512M的文件: dd命令可以轻易实现创建指定大小的文件,如 dd if=/dev/zero of=test bs=1M count=1000 会生成一个1 ...

  7. Linux基础命令---htpasswd创建密码文件

    htpasswd htpasswd指令用来创建和更新用于基本认证的用户认证密码文件.htpasswd指令必须对密码文件有读写权限,否则会返回错误码. 此命令的适用范围:RedHat.RHEL.Ubun ...

  8. linux下使用vim创建编辑文件

    vi/vim 使用实例 如果要想用vim/vi创建一个文件(使用命令): vim test.txt   不管文件存在与否 直接输入 vi 文件名 就能够进入 vi 的一般模式 按下 i 进入输入模式( ...

  9. mysql启动失败:不能创建pid文件

    2016-03-09T07:51:38.905444Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/ ...

随机推荐

  1. .NET Core微服务之基于IdentityServer建立授权与验证服务(续)

    Tip: 此篇已加入.NET Core微服务基础系列文章索引 上一篇我们基于IdentityServer4建立了一个AuthorizationServer,并且继承了QuickStartUI,能够成功 ...

  2. Python爬虫入门教程 42-100 爬取儿歌多多APP数据-手机APP爬虫部分

    1. 儿歌多多APP简单分析 今天是手机APP数据爬取的第一篇案例博客,我找到了一个儿歌多多APP,没有加固,没有加壳,没有加密参数,对新手来说,比较友好,咱就拿它练练手,熟悉一下Fiddler和夜神 ...

  3. HandlerInterceptor拦截实现对PathVariable变量的读取

    Http请求拦截作用 拦截后可以修改请求体 拦截后可以作一些其它统一的操作 问题提出 对于很多时间需要拦截很多Http请求,然后去获取一些参数,这些参数可能是querystring串,也可能是路由上的 ...

  4. Abp中使用可视化的日志面板

    Abp中使用可视化的日志面板 如果你还不了解LogDashboard请看这里. ABP的相关知识不做介绍如果有需要请阅读ABP官方文档 ABP是Net下非常优秀的开发框架,在中国很多的项目都正在使用它 ...

  5. 【面试】我是如何在面试别人Spring事务时“套路”对方的

    “中国最好面试官” 自从上次写了一篇“[面试]我是如何面试别人List相关知识的,深度有点长文”的文章后,有读者专门加我微信,说我是“中国最好面试官”,这个我可受不起呀. 我只是希望把面试当作是一次交 ...

  6. 浅析Servlet执行原理

    在JavaWeb学习研究中,Servlet扮演重要的作用,学好它,是后续JavaWeb学习的良好基础.无论是SSH,还是SSM,微服务JavaWeb技术,都应先学好Servlet,从而达到事半功倍的效 ...

  7. linq用法整理

    linq用法整理 普通查询 var highScores = from student in students where student.ExamScores[exam] > score se ...

  8. TrieTree

    学习链接:https://blog.csdn.net/lisonglisonglisong/article/details/45584721 前缀树解决字符串前缀匹配问题,查找单词是否存在,统计以如“ ...

  9. arcgis api 4.x for js之基础地图篇

    arcgis api3.x for js转向arcgis api4.x,我也是最近的3-4个月时间的事情,刚好公司有个webgis项目需要展示三维场景,项目选择arcgis api4.x.我纯碎记录一 ...

  10. 47.Odoo产品分析 (五) – 定制板块(2) – 为业务自定义odoo(2)

    查看Odoo产品分析系列--目录 Odoo产品分析 (五) – 定制板块(2) – 为业务自定义odoo(1) 4 添加自定义字段 定制odoo的最普通的原因就是指定到公司的附加信息.如果您正在运行一 ...