gpt4 book ai didi

c - fork /执行 : child exits when trying to redirect stdin/stdout

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:39 30 4
gpt4 key购买 nike

我正在尝试使用 fork/exec 从我的程序中控制一个类似 shell 的进程,使用管道将命令写入进程并读取其输出。如果我在没有任何重定向的情况下创建进程,它会按预期运行而不会退出 - 我可以在 ps 输出中看到父进程和子进程。但是,一旦我添加了重定向代码, child 似乎立即退出(它在 ps 中显示为“defunct”)。我不确定如何确定子进程退出的原因(我没有看到它的任何输出),所以我正在努力诊断问题。

我的代码看起来像这样:

int in[2], out[2];
FILE *in_fp, *out_fp;

pipe(in);
pipe(out);

if (fork()) {
close(in[0]);
close(out[1]);
in_fp = fdopen(in[1], "w");
out_fp = fdopen(out[0], "r");

// Here I'll use in_fp and out_fp to communicate with the child.
} else {
dup2(in[0], STDIN_FILENO);
dup2(out[1], STDOUT_FILENO);
close(in[0]);
close(in[1]);
close(out[0]);
close(out[1]);

execlp("child_process", NULL);
}

有谁知道为什么这可能不起作用,或者建议我如何获得有关子进程退出原因的更多信息?

编辑:因此 strace 显示子进程因 SIGSEGV 而崩溃,看起来它在 Py_SetProgramName 中 - 尽管还不能弄清楚原因(无法访问子进程的符号)。

最佳答案

问题可能出在对 execlp() 的调用中。

尽管从技术上讲参数列表可能为空,但标准做法是始终添加至少一个参数,即 main() 中的 argv[0] , 以及用于调用程序的实际名称。可能 python 程序使用此 arg0 作为 Py_SetProgramName() 的参数而不检查 NULL

所以改为:

execlp("child_process", "child_process", (char*)NULL);

另请注意,引用自 man execlp:

The list of arguments must be terminated by a null pointer, and, since these are variadic functions, this pointer must be cast (char *)NULL

关于c - fork /执行 : child exits when trying to redirect stdin/stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29710632/

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