繁体   English   中英

在执行ls -l | grep D时出错。 grep De

[英]Getting errors in executing ls -l |grep D | grep De

我是操作系统的新手,我正在尝试执行以下提到的以下命令,但无法解决为什么它不起作用的问题。

我正在尝试执行命令

ls -l | grep D|grep De

这是我的代码-

#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;
}

请帮助我执行此命令。 预先谢谢你

这是从您的c代码执行这些命令的更简单方法:

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

 int main ()
 {
    char command[50];

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

   return(0);
 } 

system命令将命令指定的命令名称或程序名称传递给要由命令处理器执行的主机环境,并在命令完成后返回。

如果将来命令变得太复杂,这是执行Shell脚本的另一种方法:

#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;
}

#define SHELLSCRIPT指令在C中用于定义命名常量: SHELLSCRIPT ,其中包含外壳程序脚本。

每行末尾的反斜杠\\用于在下一行中键入代码,以提高可读性。

请让我知道,如果你有任何问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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