c - 在不复制实例的情况下多次执行程序

标签 c linux daemon

我有这个应用程序,它是一个检测和监控设备的守护程序。它接受参数,然后打印可用的设备。例如

 ./udevmon -s //prints the devices that are connected to my server.

示例输出

 Device: /dev/ttyUSB0  subsystem: tty

现在,当我再次运行它以检查可用的设备时,再次键入 ./udevmon -s 它会创建具有不同进程 ID 的 ./udevmon 的第二个实例。当我键入不带参数的 ./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;       
}

最佳答案

改为在以下包装下运行您的应用程序:

killall -KILL udevmon &> /dev/null
./udevmon <ARG>

您可以使用以下脚本轻轻地杀死它,执行与上面相同的一些通知:

#!/bin/bash

exist=`ps -e | grep udevmon | wc -l`

if [ "$exist" == "0" ] ; then
# there is no instance. run it
    echo "first run"
    ./udevmon -s
else
# kill old and run again
    pid=`ps -e | grep udevmon | awk '{print $1;}'`
    if [ "$pid" != "" ] ; then
        kill $pid
        echo "kill and run"
        ./udevmon -s
    else
        echo "unable to find pid!"
    fi
fi

关于c - 在不复制实例的情况下多次执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12633322/

相关文章:

python - Linux 使用错误的 python 版本

linux - 从 fstab 的输出中跳过/数据和/分区

c# - 在 .NET Core 2 linux 守护进程中优雅地关闭通用主机

macos - Mac 守护进程 howto(由 'book' 提供)

linux - 如何在 linux 中删除两个连续选项卡中的一个选项卡

c - 在 c : func(void) vs. 中

c - GCC 中的链接错误 : selective static linking of libm. a

从命令行更改显示模式

python - celery 守护进程 - 日志文件的权限被拒绝

c - C中的sprintf和printf有什么区别?