介紹
通常后臺(tái)服務(wù)器程序都必須有且只有一個(gè)進(jìn)程,那么如何單進(jìn)程呢?
本例子是通過(guò)flock函數(shù)對(duì)/var/run/myserver.pid記錄pid文件的進(jìn)行加鎖
- 若加鎖不正常,說(shuō)明后臺(tái)服務(wù)進(jìn)程已經(jīng)在運(yùn)行了,這時(shí)則直接報(bào)錯(cuò)退出
- 若加鎖成功,說(shuō)明后臺(tái)服務(wù)進(jìn)程沒(méi)有在運(yùn)行,這時(shí)可以正常啟用進(jìn)程
后臺(tái)服務(wù)程序單進(jìn)程控制
詳細(xì)不多說(shuō),直接看代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#define PID_BUF_LEN (20)
#define RUN_PID_FILE "/var/run/myserver.pid"
//服務(wù)進(jìn)程單實(shí)例運(yùn)行
//返回值: 1--正在運(yùn)行,0--未運(yùn)行,-1--出錯(cuò)
int server_is_running()
{
int fd = open(RUN_PID_FILE, O_WRONLY|O_CREAT);
if(fd < 0)
{
printf("open run pid err(%d)! %s\n", errno, RUN_PID_FILE);
return -1;
}
// 加鎖
// LOCK_SH 建立共享鎖定。多個(gè)進(jìn)程可同時(shí)對(duì)同一個(gè)文件作共享鎖定。
// LOCK_EX 建立互斥鎖定。一個(gè)文件同時(shí)只有一個(gè)互斥鎖定。
if(flock(fd, LOCK_EX|LOCK_NB) == -1)
{
//加不上鎖,則是服務(wù)正在運(yùn)行,已上鎖了
printf("server is runing now! errno=%d\n", errno);
close(fd);
return 1;
}
// 加鎖成功,證明服務(wù)沒(méi)有運(yùn)行
// 文件句柄不要關(guān),也不要解鎖
// 進(jìn)程退出,自動(dòng)就解鎖了
printf("myserver is not running! begin to run..... pid=%ld\n", (long)getpid());
char pid_buf[PID_BUF_LEN] = {0};
snprintf(pid_buf, sizeof(pid_buf)-1, "%ld\n", (long)getpid());
// 把進(jìn)程pid寫入到/var/run/myserver.pid文件
write(fd, pid_buf, strlen(pid_buf));
return 0;
}
int main(void)
{
//進(jìn)程單實(shí)例運(yùn)行檢測(cè)
if(0 != server_is_running())
{
printf("myserver process is running!!!!! Current process will exit !\n");
return -1;
}
while(1)
{
printf("myserver doing ... \n");
sleep(2);
}
return 0;
}
運(yùn)行結(jié)果
運(yùn)行程序,可知進(jìn)程pid是6965
[root@lincoding singleprocess]# ./myserver
server is not running! begin to run..... pid=6965
myserver doing ...
myserver doing ...
myserver doing ...
myserver doing ...
myserver doing ...
myserver doing ...
myserver doing ...
myserver doing ...
/var/run/myserver.pid 也記錄此進(jìn)程的pid號(hào),ps auxf | grep myserver可知mysever進(jìn)程一直運(yùn)行著
[root@lincoding singleprocess]# cat /var/run/myserver.pid
6965
[root@lincoding singleprocess]#
[root@lincoding singleprocess]# ps auxf | grep myserver
root 6965 0.0 0.0 3924 460 pts/0 S+ 00:32 0:00 | \_ ./myserver
root 9976 0.0 0.0 103256 856 pts/1 S+ 00:35 0:00 \_ grep myserver
[root@lincoding singleprocess]#
此時(shí),再運(yùn)行myserver程序,這時(shí)會(huì)報(bào)錯(cuò)退出,因?yàn)闄z測(cè)到myserver程序已經(jīng)在運(yùn)行中,不可以起另外一個(gè)進(jìn)程,從而達(dá)到了后臺(tái)服務(wù)程序單進(jìn)程控制
[root@lincoding singleprocess]# ./myserver
server is runing now! errno=11
myserver process is running!!!!! Current process will exit !
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。