Chinaunix首页 | 论坛 | 博客
  • 博客访问: 28313
  • 博文数量: 5
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 130
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-06 16:00
文章分类
文章存档

2011年(1)

2008年(4)

我的朋友
最近访客

分类: LINUX

2008-04-08 10:05:17

Sometimes you only want one instance of your program, i.e. one process running at any given time. I implemented this using two methods: by checking if the program is already running and by blocking on a file descriptor.

1. by checking if the program is already running

For this to work properly, you must ensure that the program name is unique. I used the following code in a MiniGUI program, but it always died. I have not debugged it.

/*
 * usage example: ./check-process getty
 */

#include
#include
#include

int main (int argc, char* argv[]){
    FILE* fp;
    char buf[512];
    char* p;
    char* process;
    int count = 0;
     
      process = argv[1];
     
    fp = popen ("ps -e", "r");
    if (!fp){
        fprintf (stderr, "popen failed\n");
        exit (EXIT_FAILURE);
    }
   
    while ( (p = fgets (buf, sizeof(buf), fp)) != NULL ){
        if (strstr (buf, process)){
            count++;
            fprintf (stderr, "%s is running\n", process);
        }
    }
   
    if (count == 0)
        fprintf (stderr, "no %s is found in current processes\n", process);
         
    pclose (fp);
   
    return 0;  
}

2. by blocking on a file descriptor

    fd_lock = open ("/tmp/.photoframe-proc-check", O_CREAT | O_RDWR | O_NONBLOCK);
    if (fd_lock < 0){
        perror ("open");
        exit (EXIT_FAILURE);
    }
       
    //second instance of this program will fail flock and exit
    if (flock (fd_lock, LOCK_EX | LOCK_NB) < 0){
        perror ("flock");
        exit (EXIT_FAILURE);
    }

    ...

    flock (fd_lock, LOCK_UN);
    close (fd_lock);

Still a better way?

If a program is running and you use tftp to download a new version of the program to replace it, tftp will fail, saying that text file is busy. How does tftp tell the text file is busy? Is the method used by tftp a better way to do what we want here?

阅读(488) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:Scaling MiniGUI mGi Soft Keyboard

给主人留下些什么吧!~~