Aaron
Aaron

Reputation: 359

Use exec/fork to run external process

I am using C++ and trying to run a shell command in an external process. Here is the code I have so far:

pid_t pid;
pid = fork();
if(pid == 0){ 
    execv(args[0],args);
} else {
    wait();
}

My first problem is that I need to get the output from the shell command passed to exec and I do not know how to get that. After running the code above the main program also duplicates itself and I am not sure why.

Upvotes: 0

Views: 1676

Answers (1)

KQ.
KQ.

Reputation: 922

args[0] is presumably the name of the running program, so it will fork and then exec itself.

In order to collect output, you will need to arrange to explicitly pass it. The Unix pipe() call is frequently used for this.

Upvotes: 1

Related Questions