Let's start with 1 pipe such as ex: "ls | grep hello"
What I'm trying to do is to split the *args[] into 2 that one contains "ls" (left-of-the-pipe command) and the other contains "grep hello" (right command) -> so I can execute the child pipe as producer and parent as consumer.
My problem is it seems like I can't create another char *args1[] because it would mess up the current args[] that passed in.
I search everywhere and tried "memcpy or strcpy" but didn't solve the problem, since I might not use them correctly.
Thanks for your help :)
void exec_pipe(char *args[], pid_t childpid, int pipeno1)
{
//pipeno1 is the integer position of the pipe in the args.
int pd[2];
pipe(pd); //creates the pipe
cout << args[0] << endl; // <-- This output fine with the correct content of args[0]
char *args1[pipeno1];
cout << args[0] << endl; // <-- This output nothing, seems like the content is messed up after creating args1
for (int i=0; i<pipeno1; i++)
args1[i] = args[i];
if ((childpid = fork()) == 0)
{
// child does producer
close(1); // close stdout
dup(pd[1]); // dup into stdout
close(pd[0]); close(pd[1]); // goody
execvp(args1[0], args1);
}
// parent does consumer
close(0); // close stdin
dup(pd[0]); // dup into stdin
close(pd[0]); close(pd[1]); // goody
execvp(args[pipeno1+1], args);
}