gpt4 book ai didi

c - 对子进程的操作 C

转载 作者:行者123 更新时间:2023-11-30 15:13:58 25 4
gpt4 key购买 nike

我想创建一个程序:

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

最佳答案

因为当你 fork 时,你的 child 立即退出,这很可能当你试图杀死他们时他们已经死了(可能,不是强制性的,这取决于调度程序)。列表也是如此:您看到的进程是一些尚未退出的剩余进程以及进程“ps”本身,由您的第一个进程创建。

关于c - 对子进程的操作 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com