簡體   English   中英

子進程的操作C

[英]Operations on child processes C

我想創建一個程序:

  1. 創建子進程
  2. 列出所有子進程
  3. 讀取PID以殺死子進程之一
  4. 再次列出所有子進程。

我的代碼:

#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 
#include <string.h>

int main(void) {
    int c = 0;
    printf("How many: ");
    scanf("%d", & c);

    int i = 0;

    for (i = 1; i <= c; i++) {
        pid_t pid = fork();

        if (pid == 0) {
            exit(0);
        }
    }

    ListOfChildren();
    int t;
    printf("Kill child: ");
    scanf("%d", & t);

    char test[50];
    snprintf(test, sizeof(test), "kill -15 %d", t);
    system(test);
    ListOfChildren();
    return 1;

}

int ListOfChildren() {
    char str[50] = "ps -o pid --ppid ";
    char ppid[7];
    sprintf(ppid, "%d", getpid());
    strcat(str, ppid);
    system(str);
    return 1;
}

它創建了一些進程,但是最后一個進程不存在? 而且我什至不能殺死一個……為什么當我要3時它顯示4個進程?

因為當您分叉時,您的孩子會立即退出,這很可能是您在試圖殺死他們時已經死了(可能是非強制性的,取決於調度程序)。 列出同樣的東西:您看到的進程是尚未退出的剩余進程中的一些,以及進程“ ps”本身(由第一個進程創建)。

回答您的第一個問題

最后一個進程不存在,因為它是程序中system命令派生的子進程,一旦命令返回,該進程將不再有效,因此您將無法看到該進程。 有關更多詳細信息,請查看系統命令的手冊頁

http://linux.die.net/man/3/system

對於第二個問題,確實您的子進程已經完成執行,並且它們已經失效。 您可以通過執行在程序中檢查它們

ps -ef | grep defunct

在您從“殺死孩子:”輸入一些選項之前。 然后,您將看到在程序中分叉的子進程已失效。

他們已經消失的原因是

父進程必須通過使用wait()系統調用來明確注意子進程的消亡。

http://en.linuxreviews.org/Defunct_process

您通常無法使用

kill -9 pid

這就是為什么“殺手”對您不起作用的原因。

暫無
暫無

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

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