Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

implement ls | wc in C code

Posted on 2004-11-25
10
Medium Priority
?
3,037 Views
Last Modified: 2012-05-05
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.
0
Comment
Question by:libin_v
  • 2
  • 2
  • 2
  • +2
8 Comments
 
LVL 23

Expert Comment

by:Mysidia
ID: 12679317
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
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 12680723
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
 
LVL 5

Author Comment

by:libin_v
ID: 12680908
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 12680934
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
 
LVL 86

Expert Comment

by:jkr
ID: 12681320
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
 
LVL 5

Author Comment

by:libin_v
ID: 12682482
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
 
LVL 23

Accepted Solution

by:
Mysidia earned 1000 total points
ID: 12683619
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
 
LVL 22

Expert Comment

by:grg99
ID: 12684315
Remember of course that file names are not what wc counts!

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question