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);    

Recommended Answers

All 2 Replies

I can't see an obvious explanation for why your second cout statement doesn't print anything. However, one flaw in this function is that the args[] and args1[] arrays must end with a 0 as their last element (a Unix requirement, not a C++ one) -- otherwise how does execvp() know where the arguments end?. In the child's execvp(), args1 isn't terminated with a 0; and in the parent's execvp(), the second argument should be args+pipeno1+1 .

Your function works for me if I fix that, so maybe your args array and pipeno1 aren't set up the way you think they are.
You might try restructuring the code a little to do all the args[] string manipulation without doing the fork/exec. Verify that the strings are as expected, then add the fork/exec. In the current form, since the code goes on to fork/exec and starts manipulating file descriptors, you may be getting I/O interactions that are hiding your cout statements.

Thanks for ur input. I figured out the problem which I didn't setup the 2 pipe args in correctly prior to the pass in. everything works fine now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.