gpt4 book ai didi

c - 如何获取 fork() 中的 execvp 错误?

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:27 27 4
gpt4 key购买 nike

我有以下代码。

我的问题在代码中

     int main() {

....

if ((uproc.pid = fork()) == -1) {
return -1;
}

if (uproc.pid == 0) {
/* child */

const char *argv[3];
int i = 0;
argv[i++] = "/bin/sh";
argv[i++] = "/my/script.sh";
argv[i++] = NULL;

execvp(argv[0], (char **) argv);
exit(ESRCH);

} else if (uproc.pid < 0)
return -1;

/* parent */
int status;
while (wait(&status) != uproc.pid) {
DD(DEBUG,"waiting for child to exit");
}

// If /my/script.sh exit accidentally in some place with error.
// can I catch this error right here?
......
}

最佳答案

子进程的退出状态由 wait 函数在 status 变量中提供。

您可以使用 WEXITSTATUS 宏获取退出状态,但前提是程序正常退出(即调用 exit 或从其 main 返回) > 函数):

if (WIFEXITED(status))
printf("Child exit status: %d\n", WEXITSTATUS(status));
else
printf("Child exited abnormally\n");

阅读manual page for wait获取更多信息。

关于c - 如何获取 fork() 中的 execvp 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13532391/

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