我有这个应用程序,它是一个用于检测和监视设备的守护程序。它接受参数,然后打印哪些设备可用。例如多次执行程序而不复制实例
./udevmon -s //prints the devices that are connected to my server.
样本输出
Device: /dev/ttyUSB0 subsystem: tty
现在,当我再次运行它来检查哪些设备可用,打字./udevmon -s
再次它将创建一个具有不同的进程id ./udevmon的第二instace。当我输入没有参数的./udevmon时,它会用不同的进程ID再次创建一个新的实例,现在总共有3个./udevmon进程。这会让我的系统变慢,因为我需要多次运行./udevmon。
如何运行我的应用程序,以便它只创建一个实例。例如,当我再次键入./udevmon -s或./udevmon时重新启动它?
以下是示例代码。
int main (int argc, char *argv[])
{
mon_init(); // initialize device monitor
scan_init(); // initialize device scan
//Fork the Parent Process
pid = fork();
if (pid < 0) { exit(EXIT_FAILURE); }
//We got a good pid, Close the Parent Process
if (pid > 0) { exit(EXIT_SUCCESS); }
//Change File Mask
umask(0);
//Create a new Signature Id for our child
sid = setsid();
if (sid < 0) { exit(EXIT_FAILURE); }
//Change Directory
//If we cant find the directory we exit with failure.
if ((chdir("/")) < 0) { exit(EXIT_FAILURE); }
while((c=getopt(argc, argv,"s")) != -1) {
switch(c) {
case 's': scan_run(); break;
default: printf("wrong command\n");
}
}
//Main Process
while(1) {
start_mon();
}
udev_unref(udev);
return 0;
}
保持运行状态:
你可以轻轻地使用下面的脚本做同样与上面一些通知杀呢? –
如何创建一个'udevmon.pid'文件,它表示一个进程已经在运行?当进程存在时,当然,你必须删除文件。这样你可以防止产生新的进程。 –
是让它运行,因为如果设备被移除并添加,它也会报警。它在终端中打印。它运行在后台..如果我再次运行该程序,它不应该创建该程序的第二个实例.. – demic0de