简体   繁体   English

pclose()不会给我进程退出代码

[英]pclose() won't give me the process exit code

I've got a strange problem here. 我这里有一个奇怪的问题。

I wrote some C++ code with uses popen(3) , read(3) and pclose(3) to run various shell commands, parse their output, and do some other stuff. 我使用popen(3)read(3)pclose(3)编写了一些C ++代码,以运行各种shell命令,解析其输出并执行其他操作。 The program seems to work well. 该程序似乎运行良好。

Then I extracted some of the code into a shared library and tried to use it from a C# program running under Mono. 然后,我将一些代码提取到共享库中,并尝试在Mono下运行的C#程序中使用它。 Now the C++ code doesn't work at all. 现在,C ++代码根本不起作用。

Running the code in GDB, it seems that pclose(3) always unconditionally returns -1 rather than the real exit code of the child process. 在GDB中运行代码,似乎pclose(3) 总是无条件地返回-1,而不是子进程的实际退出代码。

Watching strace , it seems that wait4(2) fails with ECHILD . 看着strace ,似乎ECHILD wait4(2)失败了。 And, as best as I can tell, it does that because SIGCHLD is being delivered to one of Mono's other threads, which promptly does several wait4(2) calls, and then carries on with its day. 而且,据我所知,这样做是因为将SIGCHLD传递到Mono的其他线程之一,该线程立即执行几个wait4(2)调用,然后继续执行。

Doing some Google searching, it appears the kernel chooses a thread at random to send SIGCHLD to. 在做一些Google搜索时,似乎内核会随机选择一个线程来发送SIGCHLD (In other words, in a multithreaded program it is guaranteed to always choose the "wrong" thread.) (换句话说,在多线程程序中,保证总是选择“错误”线程。)

Obviously I have no control over what the Mono runtime decides to do. 显然,我无法控制Mono运行时的决定。 So how can I invoke external processes and reliably get their exit codes? 那么,如何调用外部进程并可靠地获取其退出代码?

pclose() never returns the real exit code from the child process. pclose()从不从子进程返回真正的退出代码。

pclose rather returns the value of the stat_loc parameter to the wait() call. pclose宁可将stat_loc参数的值返回给wait()调用。

In cases, when waitpid() with the process id of the child returns -1 , pclose() returns -1 as well. 在某些情况下,当具有子进程ID的waitpid()返回-1pclose()返回-1

This may happen if you have broken code in other threads that waits for arbitrary child processes instead of only waiting for self created child processes. 如果您在其他线程中等待了任意子进程而不是仅等待自行创建的子进程的代码中断,可能会发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM