I have this application which is a daemon program that detects and monitors devices. It accepts arguments which then prints what devices are available. e.g.
./udevmon -s //prints the devices that are connected to my server.
Sample Output
Device: /dev/ttyUSB0 subsystem: tty
Now when I run it again to check what devices are available, typing ./udevmon -s again it creates a second instace of ./udevmon with different process id. When I type ./udevmon without arguments it creates a new instance again with different process id so a total of 3 processrs of ./udevmon now. In time this will make my system slow because I need to run ./udevmon many times.
How can I run my application so it only creates a single instance. e.g restarting it when i type ./udevmon -s or ./udevmon again?
Here’s sample code.
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;
}
Run your application under the following wrap instead:
You may kill it softly using following script doing the same as above with some notifications: