SIGSEGV 使用 fork 运行 geant4

SIGSEGV using fork to run geant4

本文关键字:geant4 运行 fork 使用 SIGSEGV      更新时间:2023-10-16

当我运行使用 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,即使我使函数内联。我真的很想知道发生了什么。

我想

至少就函数用法而言,我已经弄清楚了。 我把

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有关。