Creating new process on Linux
04:25 17 Nov 2025

I am having trouble creating a sequence of independent processes on Linux.

Here's what I'm doing:

pid_t LaunchNewConsole( const std::string& cmd, const std::string& title ) {
    const char* term_exe = "xterm";

    std::vector args;
    args.push_back(term_exe);
    args.push_back("-title");
    args.push_back(title);
    args.push_back("-e");
    args.push_back("/bin/sh");
    args.push_back("-c");
    
    args.push_back("exec " + cmd);

    std::vector argv_c;
    for (const std::string& s : args) {
        argv_c.push_back(s.c_str());
    }
    argv_c.push_back(nullptr); 

    pid_t pid = -1;

    int ret = posix_spawnp(
        &pid,
        term_exe, 
        nullptr,
        nullptr,
        const_cast(argv_c.data()), 
        environ
    );

    if (ret!= 0) {
        throw std::system_error(ret, std::system_category(), "posix_spawnp failed for xterm");
    }

    return pid;
}

I am launching the same C++ executable.

A random number of processes are corrupted, resulting in a "malloc() error." It seems that some variables' memory is wrongly allocated.

c++ linux pid