• C

implement ls | wc in C code

I wanted to write a c code to implement
ls | wc
say ls and wc is in /bin.

I know how to redirect a file eg ls > list.txt.
I wanted to know if ls | wc works with the same logic as redirection? If yes, please give me the code.

I also heard that we can use the pipe().
Please implement ls | wc using pipe() in C.
LVL 5
libin_vAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MysidiaCommented:
If you just want to invoke the command from within your C program and get the result,
calling pipe() directly seems way overkill.   I would tend to say use popen() and rely on
the implementation of redirection provided by the shell.

What are you trying to accomplish: i.e. why do you want to implement
such an esoteric command like "ls |wc" using pipe() in C?

I think it might be better to just enumerate the files with opendir() readdir() and count
the lengths of filename strings, and ignore /bin/ls and /bin/wc  entirely

to accomplish whatever your program needs this information for: certainly it will win you
more in terms of speed than doing redirection and pipe() will
0
Jaime OlivaresSoftware ArchitectCommented:
It is the same situation for ls

ls > list.txt       Redirects to a file
ls | wc            Redirects to another application (pipe)

From 'ls' side, it just print all output to the standard output (stdout), normally the console.

About wc side, this applications take its input from standard input (stdin), normally the console. So you can invoke wc this way:
wc <list.txt       Input from a file
ls | wc             Input from an application

So, in conclusion, there is not a special handling for these operations, just have to input and output from/to console with simple printf() and scanf() or fread()/fwrite() operations to/from stdout/stdin.

Good luck,
Jaime.
0
libin_vAuthor Commented:
Thank PST,
But want to do it with ls and wc.

Thanks Jaime.
As I told U I do want how to redirect to/from a file. But I want to implement to both ls & wc, since both are new process(using fork).
0
How do you know if your security is working?

Protecting your business doesn’t have to mean sifting through endless alerts and notifications. With WatchGuard Total Security Suite, you can feel confident that your business is secure, meaning you can get back to the things that have been sitting on your to-do list.

Jaime OlivaresSoftware ArchitectCommented:
If you want to avoid synchonization issues between process you can do this:

1st phase:
ls >temp.txt

2nd phase:
wc <temp.txt >result.txt
0
jkrCommented:
If you basically want to count the files in a directory, you could use

#include <sys/types.h>
#include <dirent.h>

unsigned int countfiles(char* pPath) {

unsigned int count = 0;
struct dirent* pEnt = NULL;
int n;
DIR* pDir = opendir(pPath);

while(pEnt = readdir(pDir)) {

    if ( !strcmp(pEnt->d_name, ".") && !strcmp(pEnt->d_name, "..")) count++; // skip "." and ".."
}

closedir(pDir);

return count;
}

}
0
libin_vAuthor Commented:
Thanks Guys,
But listen I need to demonstrate how piping works in a shell. The code below works fine, but since popen() deals with commands same as the system(), I am not able to do job control as sending to foreground or background.

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>

int main()
{
      FILE *stream;

      stream = popen ("//bin//ls", "w");
      pclose(stream);
      stream = popen ("//bin//cat", "r");
      pclose(stream);

      /* cannot control the cat process;
            eg: ls | cat&
      */
}

I have written a code for piping, which I can later inco-operate the job control (as bcakground or foreground). But when executing, it gives me errors as "bad file descriptor". Please rectify this code.

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>

int main()
{
      pid_t pid;
      int status;
      int some[2];

      if( pipe (some) == 0 )
      {
            pid = fork();
            if( pid == 0 )
            {
                  close (some[0]);
                  fclose (stdout);
                  stdout = fdopen (some[1], "w");
                  execl ("//bin//ls", "ls", NULL);
                  _exit(0);
            }
            else
            {
                  waitpid (pid, &status, 0);
                  pid = fork();
                  if( pid == 0 )
                  {
                        close (some[1]);
                        fclose (stdin);
                        stdin = fdopen (some[0], "r");
                        execl ("//bin//cat", "cat", NULL);
                        _exit(0);
                  }
                  else
                     waitpid (pid, &status, 0);
            }
      }
}
0
MysidiaCommented:
One issue here is that re-assigning  stdin and stdout  does not redirect
these streams in the programs you are transferring control to.

Of course assigning the variable to a new value will not effect what
stdin/stdout are assigned to in child processes, even if they use libc

To re-direct streams you literally need the dup system call.
See http://mkssoftware.com/docs/man3/dup2.3.asp

Why are you using double slashes //  in filenames?

And why are you calling exit() rather than _exit() after an execl() ?

Silently failing on error codes is sort of bad, especially where you're trying to
figure out why it isn't working.

[The exit after exec() is only reached if exec() failed due to some error]

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
grg99Commented:
Remember of course that file names are not what wc counts!

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.