Replicate in C++, in Unix, this command: ps -A | grep argv[1] | wc -l

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kingfisher01
    New Member
    • Jan 2010
    • 1

    Replicate in C++, in Unix, this command: ps -A | grep argv[1] | wc -l

    Hi,

    I'm in unix trying to code a c++ program to replicate this command:

    ps -A | grep argv[1] | wc -l.

    Here is what I have, which doesn't work, and I'm totally lost. Can anyone please help me ? !!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!

    #include <iostream>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <unistd.h>
    #include <stdlib.h>


    using namespace std;

    int main(int argc, char *argv[])
    {
    int pid,pid1,pid2;
    int a[2];
    int rv;
    pipe(a);


    if ((pid = fork() == 0))
    {

    if ((pid1 = fork() == 0))
    {

    dup2(a[1],1);
    close(a[1]);
    close(a[0]);

    if ((pid2 = fork()) == 0)
    {

    dup2(a[1],1);
    close(a[1]);
    close(a[0]);
    execlp("/bin/ps","ps","-A",NULL);
    }
    else
    {
    dup2(a[0],0);

    close(a[1]);
    close(a[0]);
    execlp("/bin/grep" , "grep" ,argv[1], NULL );
    }

    }
    cout << "back to child" << endl;
    execlp("/usr/bin/wc" , "wc" , "-l", NULL );
    }
    else
    {
    wait(&rv);
    }


    return 0;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    if ((pid = fork() == 0))              <<?
    {
    
    if ((pid1 = fork() == 0))             <<?
    {
    
    etc...
    
    if ((pid2 = fork()) == 0)
    {
    I didn't look at the logic butin the fist two cases, the == operator will execute first due to its higher precedance than the = operator.

    The last case looks right.

    Comment

    Working...