来自fork()的子进程在进程结束前终止



关于C/C++中进程的快速问题。当我使用fork((在我的main中创建两个进程时,在我的子进程上,我调用一个extern API来获取bool向量并通过管道将其发送给父进程,但当我调用API时,他会立即杀死子进程,而不首先通过管道发送向量。你们为什么认为会发生这种事?代码是这样的:

//main.cpp 
#include "main.hpp"
int main(){
pid_t c_pid = fork();
if(c_pid == 0) {
std::cout << "Code From here implements Child process"<<      std::endl;
API::Api_Get_Method(); // Child dies here 
std::cout << "Finish Child process " << std::endl;
std::exit(EXIT_SUCCESS); // But should die here 
}
else{
wait(nullptr)
std::cout << "Code From here implements Parent process Id     : " << std::endl;
std::cout << "Finish Parent process " << std::endl;
}
}
//main.hpp
namespace API{
void Api_Get_Method(){
// Do stuff 
// Print the result of the Stuff
}
}
```

使用else语句,它将运行"等待(nullptr(";对于所有不为零的pid,这不一定只是父级。此外,如果你在父进程中等待(nullptr(,它会等到所有子进程都终止后再继续(这很好,因为它们没有被孤儿化(。

理想情况下,fork((中的子级应该终止,因为如果不终止,它们将被困为进程树中未被父级引用的已分配空间。这会消耗RAM并降低线程运行速度。考虑到很多这样的情况,可能需要重新启动系统。简而言之,这只是内存和线程资源分配。

最新更新