user997112
user997112

Reputation: 30605

C++ fork process but not as child

I have a command which provides diagnostic information about a running process. I would like to trigger/execute this command just before the process crashes and capture the output to stdout/file.

However, this command is not able to run as a child of the process it monitors. The command is detecting this. It needs to fork as a separate parent process.

Is there a way to spawn a new process, executing the command but not as a child?

Upvotes: 4

Views: 440

Answers (1)

Stephen Newell
Stephen Newell

Reputation: 7828

Here's a very basic example using the method I asked about in a comment:

#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    int result = fork();
    if(result == 0) {
        int fd = open("test", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
        assert(fd >= 0);
        int result = dup2(fd, STDOUT_FILENO);
        assert(result != -1);
        char * const argv[] = {"ls", NULL};
        char * const env[] = { NULL };
        result = execve("/bin/ls", argv, env);
        assert(result != -1);
    }
    return 0;
}

You'll have to tweak it for your needs, but this will store the results of ls in the file "test". The trick is that dup2 replaces the standard out file descriptor STDOUT_FILENO with a copy of the file descriptor to our newly opened file, so ls's output is redirected.

I think you'll be able to use this to get the output from your command.

Upvotes: 3

Related Questions