gpt4 book ai didi

c - 杀死运行系统 shell 命令的子进程

转载 作者:太空狗 更新时间:2023-10-29 11:29:27 25 4
gpt4 key购买 nike

在我的父进程中,我创建了一个执行 system("find/-print") 的子进程。从父进程内部,当我尝试使用 kill(childProcPID, SIGTERM) 终止此子进程时,它不会立即终止。系统命令继续在控制台上打印输出。

示例代码如下:

int main(void) {

pid_t childProc = fork();
switch (childProc) {
case -1:
perror("fork() error");
exit(EXIT_FAILURE);
case 0:
system("find / -print");
printf("if I use kill(pid, SIGTERM) control doesnt reach here");
exit(EXIT_SUCCESS);
default:
;
int i = 500000;

//No a great way to put sleep
//but its just temp
while (i != 0) {
--i;
}

kill(childProc, SIGTERM);
break;
}

printf("Exit!!!!!!");
return EXIT_SUCCESS;
}

请告诉我我做错了什么或者杀死 child 的正确方法是什么?

最佳答案

system 函数本身会创建一个子进程来执行命令(然后阻塞直到该子进程终止)。您所做的是终止调用 system 的子进程,而不是终止 system 产生的子进程。

关于c - 杀死运行系统 shell 命令的子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143720/

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