【问题标题】:How to execute the command ls|sort -r in C using pipe and fork()?如何在 C 中使用 pipe 和 fork() 执行命令 ls|sort -r?
【发布时间】:2021-04-06 08:31:09
【问题描述】:

我试图为学校项目解决这个问题,但我不明白如何在管道中打开和关闭读写: 问题是:创建一个执行以下命令 ls| 的 C 程序使用管道排序 -r 并创建 fork() 和 dup()

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 创建管道:int fd[2]; pipe(fd); 关闭一侧:close(fd[n]) 写入一侧:write(fd[1], b, s)。阅读:read(fd[0], b, s)
  • 我发布了我的作品,你可以看看吗?

标签: c pipe fork exec dup


【解决方案1】:

我通常不会容忍发布家庭作业问题的解决方案,但互联网上有足够多的糟糕代码,我认为我会发布我认为不是糟糕的代码。也许我这么想是冒昧的,但是:

/* Execute ls | sort -r */

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

static void xpipe(int *fd) { if( pipe(fd) == -1 ){ err(1, "pipe"); } }
static void xdup2(int a, int b) { if( dup2(a, b) == -1 ){ err(1, "dup2"); } }
static void xclose(int fd) { if( close(fd) == -1 ){ err(1, "close"); } }

static void
execute(int *fd, char **cmd, int w)
{
        switch( fork() ){
        case -1:
                err(EXIT_FAILURE, "fork");
        case 0:
                xdup2(fd[w], w);
                xclose(fd[0]);
                xclose(fd[1]);
                execvp(cmd[0], cmd);
                perror("execvp");
                exit(EXIT_FAILURE);
        }
}

int
main(void)
{
        int rv = EXIT_SUCCESS;
        char *ls[] = { "ls", NULL };
        char *sort[] = { "sort", "-r", NULL };
        int fd[2];
        xpipe(fd);
        execute(fd, ls, 1);
        execute(fd, sort, 0);
        xclose(fd[0]);
        xclose(fd[1]);
        for( int i = 0; i < 2; i++ ){
                int status;
                wait(&status);
                if( ! WIFEXITED(status) || WEXITSTATUS(status) ){
                        rv = EXIT_FAILURE;
                }
        }
        return rv;
}

【讨论】:

  • 感谢您花时间解决我的问题。实际上,我的问题是在使用 exec 系统调用时。我知道在使用 exec 之前应该打开和关闭管道的某些末端,但我不知道应该关闭什么以及应该打开什么。你的代码似乎比我应该交还的更专业和复杂。我将发布我认为可能正确的代码
  • 要确定要关闭哪些文件描述符,您应该数一数。在调用 exec* 之前,您希望只有 3 个打开的文件描述符,它们应该是 0、1 和 2。这意味着您要适当地复制任何管道末端并关闭所有内容(包括被复制的管道末端) d--您不需要或不想拥有其中 2 个,所以在复制后关闭一个)。
【解决方案2】:
int main(int argc, char*argv[])
{
int fd[2];
pid_t p1,p2;
pipe(fd);
if (pipe(fd)==-1){
perror("Erreur pipe");
exit();
}

p1=fork();
if (p1==-1){
perror("Erreur fork");
exit();
}
else if (p1==0) {
close(fd[0]);
dup2(fd[1],1);
execlp("ls","ls",argv[1],0);
}

p2=fork();
if (p2==-1){
perror("Erreur fork");
exit();
}
else if (p2==0){
close(fd[1]);
dup2(fd[0],0);
execlp("sort","-r",NULL);
}
waitpid(p1,nullptr,0);
close(fd[1]);
waitpid(p2,nullptr,0);
return 0;
}
// can you have a look at this and tell me if it would work?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2013-05-28
    • 2013-03-13
    • 2018-01-03
    • 1970-01-01
    相关资源
    最近更新 更多