"ls -a | wc -l " in c

  • Thread starter ramasubramanian.rahul
  • Start date
R

ramasubramanian.rahul

i am trying to implement the unix command ls -l | wc -l
in c...( using pipes and excev)
its not working.... can anyone help me here ???
thanks in advance
rahul


#include<stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 int main()
5 {
6 int a[2] , test ;
7 pipe(a);
8 close(0);
9 dup2(a[0],0);
10 if (fork() == 0)
11 {
12 close(1) ;
13 dup2(a[1] ,1);
14 close(a[1]);
15 close(a[0]);
16 close(a[0]);
17 execlp("/bin/ls" , "ls" , "-a" , NULL );
18 }
19 else
20 {
21
22 wait (NULL);
23 execlp("/usr/bin/wc" , "wc" , "-l" );
24 }
25 }
 
K

Keith Thompson

i am trying to implement the unix command ls -l | wc -l
in c...( using pipes and excev)
its not working.... can anyone help me here ???

pipes and execv are extensions, not part of standard C. Try
comp.unix.programmer.
 
H

Hubble

i am trying to implement the unix command ls -l | wc -l
in c...( using pipes and excev)
its not working.... can anyone help me here ???
thanks in advance
rahul


#include<stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 int main()
5 {
6 int a[2] , test ;
7 pipe(a);
8 close(0);
9 dup2(a[0],0);
10 if (fork() == 0)
11 {
12 close(1) ;
13 dup2(a[1] ,1);
14 close(a[1]);
15 close(a[0]);
16 close(a[0]);
17 execlp("/bin/ls" , "ls" , "-a" , NULL );
18 }
19 else
20 {
21
22 wait (NULL);
23 execlp("/usr/bin/wc" , "wc" , "-l" );
24 }
25 }

1. There is no use to wait(NULL)
2. You should add code to check if your system calls do not fail
3. You forgot NULL at the end of the execlp of wc

This works

#include<stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int a[2] , pid;
pipe(a);
if ((pid=fork()) == 0)
{
dup2(a[1] ,1);
close(a[1]);
close(a[0]);
execlp("/bin/ls" , "ls" , "-a" , NULL );
perror("/bin/ls");
}
else if (pid>0)
{
dup2(a[0],0);
close(a[1]);
close(a[0]);
execlp("/usr/bin/wc" , "wc" , "-l", NULL ); /* add NULL
!! */
perror("/usr/bin/wc");
} else
perror("fork");
}

Adding the perror lines quickly reveiled
/usr/bin/wc: Bad address

Hubble.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top