implement your own pipe ls | wc example

Jun 4, 2015 at 11:09am
what am I doing wrong, this is part of my code for only |

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

//ignore unnecessary headers

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>


using namespace std;

int main(){

    int fd[2];

    char* cmd="ls | wc";//pipe to be coded
    char* buf[100];// memory
    pipe(fd);

    pid_t pid=fork();

    if(cmd){//just test the command

        if(pid==0){

            //close(fd[0]);
            dup2(0,fd[0]); 
            execlp("ls", "ls", NULL);
            //write(fd[1],say, 100);

        }

        else{

            //close(fd[1]);
            //int bytes=read(fd[0],buf, 100);
           
            dup2(1,fd[1]);
            read(fd[0], buf, 100);
            execlp("wc", "wc", NULL);
           
            //dup2(1,fd[1]);

            //cout<<bytes<<endl;
        }}

    return 0;
}


only executes ls
Jun 4, 2015 at 12:14pm
You need to check your return codes! Check dup2() and read(), and execlp().
Jun 4, 2015 at 4:27pm
no return codes shown...but if there is an error, which there is, then what is that exactly? Can you tell me?
Jun 5, 2015 at 6:23am
The problem is how you are using dup2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>


using namespace std;

int main(){

    int fd[2];

    const char* cmd="ls | wc";//pipe to be coded
    char* buf[100];// memory
    pipe(fd);

    pid_t pid=fork();

    if(cmd){//just test the command

        if(pid==0){

            close(fd[0]);
            dup2(fd[1], 1); 
            execlp("ls", "ls", NULL);
        }

        else{

            close(fd[1]);       
            dup2(fd[0], 0);
            execlp("wc", "wc", NULL);           
        }
    }

    return 0;
}
Jun 5, 2015 at 12:04pm
thanks a lot ...its working...one more thing..how would I implement multipipes?

like ls | sort | wc for example
Topic archived. No new replies allowed.