gpt4 book ai didi

c - 如果 execvp() 成功,子进程会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:53 26 4
gpt4 key购买 nike

我有一个关于execvp()的使用的问题,对于下面的函数,如果我在子进程中并且execvp()函数执行成功(根据man page,它不会返回),如果else {} 之外的脚本将继续工作,这意味着 execCmd() 函数是否会返回任何值?

int execCmd(char* args[10]) {
pid_t pid = fork();
if (pid < 0) {
exit(1);
} else if (pid > 0) { // parent process
/* do something */
} else {
if (execvp(*args, args) < 0) {
printf("Execution Failed!");
exit(1);
}
}
return 0;
}

提前致谢!

最佳答案

如果execvp成功,进程开始执行指定的程序。

Parent Process          Child Process
------------------- -------------------
fork()
pid_t pid = ...; pid_t pid = ...;
pid < 0 pid < 0
pid > 0 pid > 0
/* do something */ execvp(*args, args)
return 0; [main of new program]

你的程序本来可以写成

int execCmd(char** args) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}

if (pid == 0) {
execvp(*args, args);
perror("execvp");
_exit(1);
}

/* ... Do something in parent ... */
return 0;
}

此外,您可能希望等待子进程完成、返回 pid 或让子进程自动获取(通过忽略 SIGCHILD)。

关于c - 如果 execvp() 成功,子进程会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716882/

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