반응형


단일 인스턴스 데몬 실행하기  C 

http://blog.naver.com/junglehare/10080516674


 
프로세스 중 중복으로 실행되면 안되는 경우가 있다.


file lock 기능을 이용한 단일 프로세스 기동관련 함수를 만들어보자.


#include <stdio.h>
#include <stdlib.h>
#include <ftncl.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>


int lockfile(int fd)
{
        struct flock fl;


        fl.l_type = F_WRLCK;
        fl.l_start = 0;
        fl.l_whence = SEEK_SET;
        fl.l_len = 0;
        return(fcntl(fd, F_SETLK, &fl));
}


int check_single_running(char *pos)
{
        int fd;
        char PROCESS_ID[16];
        char LOCK_FILE_PATH[128];
        char PROCESS_NAME[32];


        memset(PROCESS_ID, 0x00, sizeof(PROCESS_ID));
        memset(PROCESS_NAME, 0x00, sizeof(PROCESS_NAME));
        memset(LOCK_FILE_PATH, 0x00, sizeof(LOCK_FILE_PATH));


        sprintf(LOCK_FILE_PATH, "%s/%s.pid", "/write_able_path", strstr(pos, "프로세스명"));
        log_trace(LOG_TRACE, "Debug LOCK_FILE_PATH:[%s]\n", LOCK_FILE_PATH);


        fd = open(LOCK_FILE_PATH, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);


        if(fd < 0){
                log_trace(LOG_TRACE, "Can't Open:[%s]/[%s]\n", LOCK_FILE_PATH, strerror(errno));
                exit(1);
        }


        if(lockfile(fd) < 0){
                if(errno == EACCES || errno == EAGAIN){
                        close(fd);
                        log_trace(LOG_TRACE, "Already Running:[%s]/[%s]\n", LOCK_FILE_PATH, strerror(errno));
                        return (1);
                }
                log_trace(LOG_TRACE, "Can't Lock:[%s]/[%s]\n", LOCK_FILE_PATH, strerror(errno));
                exit(1);
        }


        ftruncate(fd, 0);
        sprintf(PROCESS_ID, "%ld", getpid());
        write(fd, PROCESS_ID, strlen(PROCESS_ID)+1);
        return (0);
}


int main(int argc, char **argv)
{
int ret = 0;
ret = check_single_running(argv[0]);
if(ret !=0){
log_trace(LOG_TRACE, "duplicate Running!!");
exit(0);
}else{
log_trace(LOG_TRACE, "Single Running!!");
}
}


참조 : A.P.U.E 2판 - 13.5 Chapter
[출처] 단일 인스턴스 데몬 실행하기|작성자 메티리얼

반응형
Posted by 공간사랑
,