我有这个代码:
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
pid_t pid = fork();
if ( !pid ) {
char *aux[] = {argv[i], NULL};
execvp(aux[0], aux);
printf("\nChild %d executed %s with exit code %d\n", getpid(), aux[0], i);
_exit(i);
}
}
for (int i = 1; i < argc; i++) {
printf("Child dead\n");
wait(NULL);
}
return 0;
}
运行时,我注意到 printf(...)
after execvp on child process 从未运行过。我检查了 man exec
我发现的地方:
"The exec() family of functions replaces the current process image with a new process image."
这是否意味着除了printf
之外,_exit(i)
也不执行?如果是这样,我怎样才能杀死子进程? execvp new process image 会处理这个问题吗?
编辑:假设我想在 execvp 行之后执行 printf(或任何其他指令),如代码所示,有什么办法吗?
编辑[2]:让它更清楚。如果我有这个 block :
int main(void) {
for (int i = 0; i < 10; i++) {
pid_t pid = fork();
if (!pid) {
printf("child %d\n", getpid());
//_exit(1);
}
else {
wait(NULL);
printf("parent here\n");
}
}
return 0;
}
当 exit(1)
被注释时,事情变得疯狂起来。所以,我的疑问是:是否存在 execvp
正确执行并且原始子进程(调用 execvp 的进程)不会像 _exit(n)
调用那样退出的情况,产生如上述 block 中的结果。
最佳答案
Does this mean that besides printf, _exit(i) is also not executed?
是的。除非 execvp()
(和其他 exec 系列函数)失败,否则它将返回,并且 printf()
和 _exit()
语句将被执行。
If so, how can I kill child process? Does execvp new process image takes care of that?
execvp()
不会终止子进程 - 它甚至不知道它要替换的进程是子进程。
在大多数实际情况下,您不想“杀死”子进程。您希望使用 wait(2)
来等待子进程完成——您已经这样做了。子进程就像您的“主”进程一样是独立的;当它们的 main()
返回或通过调用 exit()/_exit 等或它们异常终止(例如,被 SIGTERM/SIGKILL 信号杀死)时,它们将退出。
关于c - execvp 新进程镜像并退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42816223/