【问题标题】:Operations on child processes C对子进程的操作 C
【发布时间】:2016-03-18 07:04:40
【问题描述】:

我想创建一个程序:

  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 个进程?

【问题讨论】:

    标签: c ubuntu process child-process


    【解决方案1】:

    回答你的第一个问题

    最后一个进程不存在,因为它是您程序中系统命令派生的子进程,一旦命令返回,该进程不再有效,因此您无法看到该进程。有关更多详细信息,请查看系统命令的手册页

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

    对于第二个问题,确实您的子进程已经完成执行,它们已经成为不复存在的进程。您可以通过执行在程序中检查它们

    ps -ef | grep defunct
    

    在您从“杀死孩子:”中输入一些选项之前。然后你会看到你在程序中分叉的子进程已经失效。

    它们失效的原因是

    父进程必须明确注意 通过使用 wait() 系统调用,孩子的死亡。

    http://en.linuxreviews.org/Defunct_process

    你不能正常用

    杀死它们
    kill -9 pid
    

    这就是为什么“杀”对你不起作用的原因。

    【讨论】:

      【解决方案2】:

      因为当你分叉时,你的孩子会立即退出,这很可能在你试图杀死他们时他们已经死了(可能,不是强制性的,这取决于调度程序)。列出同样的事情:您看到的进程是一些尚未退出的剩余进程和进程“ps”本身,由您的第一个进程创建。

      【讨论】:

      • 那么我该怎么做才能让它正确呢?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多