简体   繁体   中英

Getting errors in executing ls -l |grep D | grep De

I am new to Operating system and i am trying to execute the following command mentioned below but am not able to resolve why it does not work.

I am trying to execute the command

ls -l | grep D|grep De

This is my code --

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
    int fd[2];
    int fd2[2];
    pipe(fd);
    if(!fork())
    {
        pipe(fd2);
        if(!fork())
        {
            close(0);
            dup(fd[0]);
            close(1);
            close(fd[1]);
            dup2(fd2[1],fd[0]);
            close(fd[0]);
            execlp("grep","grep","D",NULL);
        }
        else
        {
            close(fd[0]);
            dup(fd2[0]);
            close(fd[1]);
            execlp("grep","grep","De",NULL);
        }
    }

    else
    {
        close(1);
        dup(fd[1]);
        close(0);
        execlp("ls","ls","-l",NULL);
    }
    return 0;
}

PLease help me to execute this command. Thank u in advance

Here is a easier way of executing those commands from your c code:

 #include <stdio.h>
 #include <string.h>

 int main ()
 {
    char command[50];

    strcpy( command, "ls -l | grep D|grep De" );
    system(command);

   return(0);
 } 

The system command passes the command name or program name specified by command to the host environment to be executed by the command processor and returns after the command has been completed.

Here is another way to execute shell scripts if you commands get too complex in the future:

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
ls -l | grep D|grep De"

int main()
{
puts("Will execute sh with the following script :");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT);
return 0;
}

The #define SHELLSCRIPT directive is used in C to define a named constant: SHELLSCRIPT which contains the shell script.

The back slash \\ at the end of each line is used to type the code in next line for better readability.

Please let me know if you have any questions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM