当我运行我的代码时,我遇到了一个问题,该代码使用fork创建子Geant4进程,但仅当我使用函数时。我可以连续多次调用我的函数而没有问题,所以我认为问题一定是在main终止之前发生的,因此我所关心的一切都成功地完成了。我不认为忽略错误是一种好的编程实践,即使它们不会影响结果,所以我想知道是什么导致了错误。
这是我不带函数的代码(没有SIGSEGV):
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
using namespace std;
string runFile;
cout << "Enter run macro file name: ";
cin >> runFile;
cout << "Running './disk " << runFile << "'" << endl;
const char* file = runFile.c_str();
const char* programPath =
"/home/fred/Documents/DIRC_Research/disk-build/disk";
pid_t pid = fork();
switch (pid)
{
case -1:
std::cerr << "fork() failed.\n";
exit(1);
case 0:
execl(programPath, "disk", file, NULL);
std::cerr << "execl() failed!";
exit(1);
default:
std::cout << "Process created with pid " << pid << std::endl;
int* status;
waitpid(pid, status, 0);
std::cout << "Process exited with " << WEXITSTATUS(status) << std::endl;
}
}这就是使用函数
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
void runDisk(const char*);
int main()
{
using namespace std;
string runFile;
cout << "Enter run macro file name: ";
cin >> runFile;
cout << "Running './disk " << runFile << "'" << endl;
const char* file = runFile.c_str();
runDisk(file);
return 0;
}
// Function to run disk Geant4 simulation with a run macro file
void runDisk(const char* runFile)
{
const char* programPath =
"/home/fred/Documents/DIRC_Research/disk-build/disk";
pid_t pid = fork();
switch (pid)
{
case -1:
std::cerr << "fork() failed.\n";
exit(1);
case 0:
execl(programPath, "disk", runFile, NULL);
std::cerr << "execl() failed!";
exit(1);
default:
std::cout << "Process created with pid " << pid << std::endl;
int* status;
waitpid(pid, status, 0);
std::cout << "Process exited with " << WEXITSTATUS(status) << std::endl;
}
}使用函数的代码在终止之前给出了一个SIGSEGV,即使我使函数内联。我真的很想知道发生了什么。
发布于 2014-04-01 07:47:53
我想我已经弄明白了,至少在函数使用方面是这样。我已经把
int status = 0;
waitpid(pid, &status, 0);
std::cout << "Process exited with " << WEXITSTATUS(status) << std::endl;而不是
int* status;
waitpid(pid, status, 0);
std::cout << "Process exited with " << WEXITSTATUS(status) << std::endl;现在我不再被SIGSEGV困扰。至于它在不在函数中时工作的原因对我来说仍然是一个谜,也许这与函数删除status有关。
https://stackoverflow.com/questions/22753688
复制相似问题