如果父/子异常退出,则保持分叉进程处于活动状态 (C++)

发布于 2024-11-06 12:44:05 字数 483 浏览 2 评论 0原文

我正在尝试与当前进程并行执行另一个命令行进程。但是,我意识到命令行程序有时会异常退出,这也会杀死我的主程序。

// MAIN PROGRAM
pid = fork();
char *argv[] = { stuff.. };
if (pid == 0) {
    int rc = execv("command line program...", argv);
    }

// DO OTHER STUFF HERE. 

if (pid > 0) {
    waitpid(pid, 0, 0);
}

命令行程序异常死掉后有什么办法让我的主程序继续运行吗?谢谢!

[更新]:是的,主进程正在写入命令行正在读取的文件,但它是一个普通文件,而不是管道。我收到一个段错误。

对我来说重现该错误非常困难,因为子进程不会经常崩溃。但它确实发生了。随机崩溃是命令行程序中的一个已知错误,这就是为什么我希望即使命令行死机也让我的主程序保持活动状态。

I am trying to execute another command line process in parallel with the current process. However, I realize that the command line program sometimes abnormally exits, and that kills my main program as well.

// MAIN PROGRAM
pid = fork();
char *argv[] = { stuff.. };
if (pid == 0) {
    int rc = execv("command line program...", argv);
    }

// DO OTHER STUFF HERE. 

if (pid > 0) {
    waitpid(pid, 0, 0);
}

Is there any way to keep my main program running after the command line program dies abnormally? Thanks!

[UPDATE]:Yes, the main process is writing to a file where the command line is reading from, but it is a normal file, not a pipe. I receive a segfault.

It is extremely hard for me to reproduce the bug, since the child process does not crash very often. But it does happen. Randomly crashing is a known bug in the command line program, which is why I want to keep my main program alive even if the command line dies.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白馒头 2024-11-13 12:44:05

在您的真实代码中,您是否在这里有其他内容:

if (pid == 0) {
    int rc = execv("command line program...", argv);
    // possibly more child stuff
}
else {
    // parent stuff
}

在此处提问时发布真实代码始终是一个好主意。

In your real code do you have an else here:

if (pid == 0) {
    int rc = execv("command line program...", argv);
    // possibly more child stuff
}
else {
    // parent stuff
}

It's always a good idea to post real code when asking questions here.

淡淡的优雅 2024-11-13 12:44:05
  • 使用 vfork 而不是 fork 来避免不必要的进程克隆。
  • 确保父进程收到 SIGCHLD 时不会崩溃。
  • 使用适当的 if-then-else 语句可以清楚地了解父进程中执行的代码以及子进程中发生的情况。例如,子进程和进程很可能都会执行 // DO OTHER STUFF HERE. 注释,以防 execv 失败。
  • 毕竟,使用gdb。它会告诉您崩溃发生在哪里。
  • Use vfork rather than fork to avoid unnecessary process cloning.
  • Make sure you don't crash when SIGCHLD is received by parent process.
  • Use proper if-then-else statement to make it clear what code executes in parent process and what happens in a child process. For example it is very likely that both child and process will execute code where // DO OTHER STUFF HERE. comment is in case execv fails.
  • After all, use gdb. It will tell you where the crash occurs.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文