Reputation: 53
I have a shell that has a function which eventually calls execvp(...) which gives an output. For example "echo hello" gives an output of "hello". Everything works, don't worry. I have tested it very much, I just didn't put the full code here because it is 1000 lines of code.
How can i take that output from execvp, dup2 it, and put it into a string?
I know I use dup2, but I'm not sure how.
I have these throughout my code:
char* globalString; //a global string I want to put the output into
char* myString = "one two three ";
char* append = "echo four";
int myPipe[2]; //my pipe
pipe(myPipe);
then I call my function and I want to pass the write end of pipe into it.
myfunction( ... , [pointer to write end of pipe]); //i don't know how
//ignoring previous code
cpid = fork();
if(cpid < 0){
//Fork wasn't successful
perror("fork");
return -1;
}
//in the child
if(cpid == 0){
execvp(...); // in this example, this prints "four" to stdout
//execvp returned, wasn't successful
perror("exec");
fclose(stdin);
exit(127);
}
//then more code happens
}
at the end, I want the output from exec to be put into globalString. Then I put globalString into myString, so that myString is "one two three four"
thank you.
Upvotes: 0
Views: 2254
Reputation: 35580
The snippet I use for getting output from a spawned process is:
pid_t pid = 0;
int pipefd[2];
pipe(pipefd); //create a pipe
pid = fork(); //spawn a child process
if (pid == 0)
{
// Child. redirect std output to pipe, launch process
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
execv(my_PROCESSNAME, args);
}
//Only parent gets here. make tail nonblocking.
close(pipefd[1]);
fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK);
child_process_output_fd = pipefd[0]; //read output from here
child_process_pid = pid; //can monitor this for completion with `waitpid`
Upvotes: 1