【问题标题】:How to kill old parent processes?如何杀死旧的父进程?
【发布时间】:2018-04-12 05:16:10
【问题描述】:

如何在 for 循环中杀死旧的父进程?我有以下分叉父进程

if (pid > 0){
    pid_t ppid = getppid();
    for (int parentid = ppid; parentid > 1; parentid++) {
        parentid = ppid;
        pid_t ppid = fork();
        if(ppid > 1) {
            execl("/usr/bin/elinks","elinks","google.com",(char *) NULL);
        }
        sleep(5);
    }
    exit(EXIT_SUCCESS);
}

我有一个子进程一直在运行

system("xdotool......")

我尝试将 kill(ppid,SIGTERM) 放在 for 循环中,但它被忽略了。只有将它放在循环之后才会发出终止信号,然后整个程序就会退出。父分叉不断堆积并消耗内存,因此我有必要在创建新父级时杀死旧父级。

【问题讨论】:

  • 1) 让您的父母 exec 而不是孩子似乎很奇怪。 2)kill不足;您需要使用 wait 家族中的某些东西来获取已终止的进程,否则它们会像僵尸一样继续存在。
  • 我尝试在父子节点上都使用 execl,但是让子节点循环很困难,所以我最终在 while(1) 循环中使用了 system()。我会调查等待电话,谢谢
  • 目前还不清楚您到底要做什么。首先,你不分叉父母。正常的范例是孩子的'fork/(child)exec, and as @StephenNewell said, wait`。杀死父母是违反直觉的。

标签: c++ linux pid


【解决方案1】:

您还需要确保为您的 for 循环:

pid_t ppid = getppid();

for (int parentid = ppid; parentid > 1; parentid++) {

    parentid = ppid;

    pid_t ppid = fork();

您确定您的 for 循环按预期结束吗?

如果因为fork()成功,parentid总是大于1,如何

循环是否终止?

fork函数返回0给子进程,子进程的PID返回给父进程。

因此,您可以使用此代码来确定是否 正在执行的代码是子代或父代:

pid_t pid = fork();

if (pid == 0)
{
    /* At this point, the code that is executing is the child */
}
else if (pid > 0)
{
    /* At this point, the code that is executing is the parent */
}
else 
{
    /* The fork function call failed */
}

您的代码需要区分孩子和 父母;您可以在块中使用退出系统调用 父级代码。

【讨论】:

  • 一旦execl 在父级中被击中,它将永远无法到达问题中的exit 调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 2018-10-14
相关资源
最近更新 更多