Menu Home

linux c 单例执行程序

保证系统种某个进程只有一个实例在运行,举例下面2种方法:
1. 使用popen执行ps -ef 后分析结果
2. 使用文件锁
代码如下:

第一种:
int exist(void){
    FILE* fp;
    char buf[10] = {0};
    char command[100] = {0};
    sprintf(command, "ps -ef | grep %s | grep -v grep | wc -l", argv[0]);
    printf("command : %s\n", command);
    fp = popen(command, "r");
    if(fp == NULL)
    {
        perror("popen error!");
        return -1;
    }
    if((fgets(buf, 10, fp))!= NULL)
    {
        if(atoi(buf) != 0)
        {
            printf("%s is running!", argv[0]);
        }
        else
        {
            printf("%s is not running!", argv[0]);
        }
    }
    pclose(fp);
    return 0;
}
第二种
#define LOCKFILE  "/var/run/lte8718wdt.pid"
#define LOCKMODE  (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

int lockfile(int fd)
{
    struct flock fl;
    int ret;

    fl.l_type = F_WRLCK;
    fl.l_start = 0;
    fl.l_whence = SEEK_SET;
    fl.l_len = 0; // lock the whole file

    ret = fcntl(fd, F_SETLK, &fl);
    if(-1 == ret)
        perror("set file lock error!");
    return ret;
}
int is_running(const char* filename)
{
    int fd;
    char pid[15] = {0};

    fd = open(filename, O_RDWR | O_CREAT, LOCKMODE);
    if(fd < 0)
    {
        perror("open file error!");
        return -1;
    }
    if(lockfile(fd) == -1)
    {
        if(errno == EACCES || errno == EAGAIN)
        {
            printf("%s already locked\n", filename);
            close(fd);
            return -1;
        }
    }
    ftruncate(fd, 0);
    sprintf(pid, "%ld", (long)getpid());
    write(fd, pid, sizeof(pid) - 1);
    return 0;
}

13 replies

  1. Thank you for all your valuable work on this web page. My aunt takes pleasure in managing internet research and it’s really easy to see why. All of us notice all about the powerful manner you present reliable techniques on the website and even boost response from the others on this content while our favorite child is now understanding a great deal. Enjoy the remaining portion of the year. You are performing a really great job.

  2. I simply had to appreciate you all over again. I’m not certain the things that I would’ve followed in the absence of these tips and hints contributed by you regarding my field. It was the troublesome setting in my view, nevertheless viewing a specialized form you treated that made me to weep for contentment. Extremely grateful for this information and as well , hope that you find out what a powerful job that you are getting into instructing many others all through your web page. I know that you’ve never come across any of us.

  3. Thanks so much for giving everyone a very wonderful chance to read in detail from this web site. It’s usually so fantastic and also stuffed with amusement for me and my office colleagues to search your site the equivalent of thrice weekly to read the newest guidance you will have. And definitely, I’m just usually astounded considering the spectacular tips and hints served by you. Some 2 points on this page are absolutely the most efficient we have had.

  4. I would like to show some thanks to you just for rescuing me from such a circumstance. As a result of checking throughout the the net and meeting proposals which were not helpful, I figured my life was over. Living without the answers to the issues you have solved by way of your main review is a serious case, and ones which could have in a wrong way damaged my career if I hadn’t encountered the website. The capability and kindness in touching every part was valuable. I don’t know what I would have done if I hadn’t discovered such a thing like this. I am able to at this point look forward to my future. Thanks for your time so much for this high quality and effective guide. I will not hesitate to suggest your web site to anybody who wants and needs support on this subject matter.

  5. I am glad for commenting to let you understand what a amazing discovery my wife’s princess gained using your site. She mastered numerous issues, which include what it is like to have a great coaching character to let the mediocre ones with no trouble comprehend some specialized subject matter. You really surpassed her expected results. Thanks for imparting the powerful, dependable, informative and as well as cool thoughts on your topic to Ethel.

  6. I would like to voice my appreciation for your kindness supporting women who should have help on the concern. Your personal commitment to passing the message all through turned out to be wonderfully helpful and have truly encouraged those just like me to attain their desired goals. Your personal important tips and hints signifies so much a person like me and far more to my mates. Thanks a ton; from all of us.

  7. I enjoy you because of your entire efforts on this website. Debby loves setting aside time for internet research and it is simple to grasp why. My spouse and i notice all relating to the powerful method you provide efficient thoughts by means of your website and as well as invigorate contribution from people on the article and our own simple princess is certainly becoming educated a whole lot. Have fun with the remaining portion of the new year. You are doing a pretty cool job.

  8. I am also writing to let you understand what a impressive discovery our princess developed reading yuor web blog. She noticed so many things, most notably how it is like to possess a wonderful giving spirit to make the rest effortlessly learn chosen tricky subject matter. You truly surpassed our desires. Thanks for imparting those beneficial, trustworthy, edifying not to mention cool tips on that topic to Kate.

  9. My husband and i felt quite fulfilled when Chris managed to carry out his studies from your precious recommendations he obtained from your very own web pages. It is now and again perplexing to just happen to be releasing instructions that many some other people might have been selling. And now we see we have you to be grateful to for that. Most of the illustrations you’ve made, the easy blog navigation, the relationships you can give support to foster – it is many superb, and it’s letting our son and the family recognize that that issue is cool, which is certainly incredibly serious. Many thanks for everything!

  10. I precisely had to appreciate you once again. I am not sure the things I might have followed in the absence of the actual secrets provided by you concerning such subject matter. Previously it was the challenging issue in my view, but finding out your expert form you resolved it made me to jump for fulfillment. Extremely grateful for the help and thus trust you realize what a great job that you are carrying out training men and women by way of your site. Most likely you have never come across all of us.

  11. I wish to express my admiration for your kindness supporting individuals who actually need guidance on in this content. Your personal dedication to passing the message all-around has been rather effective and have in most cases encouraged others like me to get to their goals. Your own interesting information signifies a whole lot to me and further more to my colleagues. Best wishes; from everyone of us.

  12. Thank you a lot for giving everyone such a terrific opportunity to read from this site. It’s usually so terrific plus stuffed with amusement for me and my office peers to search your blog at the very least three times in 7 days to read the newest tips you will have. And lastly, I am also always motivated with all the spectacular concepts you serve. Certain two ideas in this posting are really the simplest I have ever had.

  13. My wife and i ended up being comfortable that Jordan managed to conclude his research via the ideas he acquired in your weblog. It is now and again perplexing to simply be freely giving secrets and techniques which often a number of people may have been trying to sell. We do know we’ve got the website owner to appreciate for this. These illustrations you made, the simple blog navigation, the friendships your site give support to foster – it’s everything astonishing, and it’s helping our son and the family know that that situation is enjoyable, which is certainly especially indispensable. Many thanks for everything!

Leave a Reply