问题
I am executing a file as a daemon process. How can I stop the daemon?
int main(int argc, char **argv)
{
if ( argc != 5 )
{
printf ("Usage: %s <server> <nick> <channel> <logging>\n", argv[0]);
return 1;
}
char *startPath = malloc(sizeof(char) *100);
strcpy(startPath,"/home/.../start");
int child_pnr;
if(daemonisieren() != 0)
{
printf("damonization not possible");
exit(0);
}
printf("I am a damon \n");
if((child_pnr = fork())==0)
{
execve(startPath,argv);
}
else if (child_pnr > 0)
{
printf("I am parent and have a child \n");
wait(child_pnr);
}
printf("gone....\n");
free(startPath);
}
I presume I can kill it just like kill(childnr) but as the parent process waits for the child to finish execution which he may never do I have to have a program which knows the childnr and kills it. How can I do that?
回答1:
You can make the child's process number available using many different methods, all of which can be effective. A simple way is to just store it into a file on your system. If you look in /var/run
you will probably find many XXX.pid files doing that already.
Perhaps a better solution for your use case though is to start a new thread in your parent (or have it fork a second child) which performs a sleep for some amount of time and if that time elapses, it kills the primary child. If the primary child terminates on its own, satisfying the parent's wait, the parent can kill the "watchdog" child (or thread).
来源:https://stackoverflow.com/questions/12517482/how-to-stop-a-daemon