如何停止守护进程 [英] how to stop a daemon

查看:98
本文介绍了如何停止守护进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将文件作为守护进程执行.如何停止守护进程?

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);
}

我认为我可以像 kill(childnr) 一样杀死它,但是当父进程等待子进程完成他可能永远不会执行的执行时,我必须有一个知道 childnr 并杀死它的程序.我该怎么做?

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?

推荐答案

您可以使用许多不同的方法使子进程编号可用,所有这些方法都可以有效.一种简单的方法是将其存储到系统上的文件中.如果您查看 /var/run,您可能会发现许多 XXX.pid 文件已经这样做了.

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).

这篇关于如何停止守护进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆