如何退出一个子进程和execvp返回其状态()? [英] How to exit a child process and return its status from execvp()?

查看:689
本文介绍了如何退出一个子进程和execvp返回其状态()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的简单的定制外壳我从标准输入读取命令和execvp执行它们()。在此之前,我创建了当前进程的一个分支,我调用execvp()的子进程,之后,我调用exit(0)。

In my simple custom shell I'm reading commands from the standard input and execute them with execvp(). Before this, I create a fork of the current process and I call the execvp() in that child process, right after that, I call exit(0).

事情是这样的:

pid = fork();

if(pid == -1) {
    perror("fork");
    exit(1);
}

if(pid == 0) {
    // CHILD PROCESS CODE GOES HERE...
    execvp(pArgs[0], pArgs);
    exit(0);
} else {
    // PARENT PROCESS CODE GOES HERE...
}

现在,命令用execvp的run()可以返回正确的错误?我想处理,适当而现在,我总是调用exit(0),这将意味着子进程将永远有一个OK状态。

Now, the commands run with execvp() can return errors right? I want to handle that properly and right now, I'm always calling exit(0), which will mean the child process will always have an "OK" state.

我怎样才能从execvp返回正确的状态()调用,并把它放在出口()调用?我应该得到的int值的execvp()返回,并把它作为一个出口()参数,而不是0。这就够了,正确的?

How can I return the proper status from the execvp() call and put it in the exit() call? Should I just get the int value that execvp() returns and pass it as an exit() argument instead of 0. Is that enough and correct?

推荐答案

您需要使用 waitpid函数(3)等待(1)父code等待孩子退出,并收到错误信息。

You need to use waitpid(3) or wait(1) in the parent code to wait for the child to exit and get the error message.

的语法是:

pid_t waitpid(pid_t pid, int *status, int options);

pid_t wait(int *status);

状态包含退出状态。看手册页的,看你怎么分析它。

status contains the exit status. Look at the man pages to see you how to parse it.

请注意,你不能从子过程中做到这一点。一旦你调用 execvp 子进程的死亡(适用于所有实际用途),是的替换 EXEC 'D过程。你能达到的唯一方法退出(0)还有,如果 execvp 本身出现故障,但随后的失败不因为新节目结束。这是因为它从来没有跑开始。

Note that you can't do this from the child process. Once you call execvp the child process dies (for all practical purposes) and is replaced by the exec'd process. The only way you can reach exit(0) there is if execvp itself fails, but then the failure isn't because the new program ended. It's because it never ran to begin with.

编辑:子进程不会的真正的死亡。 PID和环境保持不变,但整个code和数据与 EXEC 'D取代的。你可以在的的数恢复到原来的子进程,除非 EXEC 失败。

the child process doesn't really die. The PID and environment remain unchanged, but the entire code and data are replaced with the exec'd process. You can count on not returning to the original child process, unless exec fails.

这篇关于如何退出一个子进程和execvp返回其状态()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆