簡體   English   中英

如何殺死舊的父進程?

[英]How to kill old parent processes?

如何在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循環中,但被忽略了。 僅將其放在循環之后才發出終止信號,但隨后整個程序退出。 父叉不斷堆積並消耗ram,因此在創建新父時殺死我的老父是必要的。

您還需要確保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 */
}

您的代碼需要區分孩子和父母; 您可以在上面的代碼塊中為父級使用退出系統調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM