创建我自己的重定向和复制管道函数

Creating my own redirect and duplicate pipe functions

我正在制作一个小程序 shell,但我的两个函数出现了一些问题。 它们有点断章取义,但我希望你能理解我正在尝试做的事情,这样我就不必 post 我的整个代码。

我的 dupPipe 函数: 我想将管道复制到 std I/O 文件描述符并关闭两个管道末端。它看起来像这样:int dupPipe(int pip[2], int end, int destinfd);。 end 告诉要复制哪个管道,READ_END 或 WRITE_END,destinfd 告诉要替换哪个 std I/O 文件描述符。

我的重定向功能: 它应该将 std I/O 文件描述符重定向到文件。 看起来像这样,int redirect(char *file, int flag, int destinfd);。 其中 flag 指示是否应读取或写入文件,destinfd 是我要重定向的标准 I/O 文件描述符。

我做了什么:

int dupPipe(int pip[2], int end, int destinfd)
{
if(end == READ_END)
{
    dup2(pip[0], destinfd);
    close(pip[0]);
}
else if(end == WRITE_END)
{
    dup2(pip[1], destinfd);
    close(pip[1]);
}
return destinfd;
}

第二个函数:

int redirect(char *filename, int flags, int destinfd)
{
if(flags == 0)
{
    return destinfd;
}
else if(flags == 1)
{
    FILE *f = fopen(filename, "w");
    if(! f)
    {
        perror(filename);
        return -1;
    }
}
else if(flags == 2)
{
    FILE *f = fopen(filename, "r");
    if(! f)
    {
        perror(filename);
        return -1;
    }
}
return destinfd;
}

感谢您提供的任何帮助,我做错了什么或没有完成我编写的想要的功能?谢谢

redirect 函数似乎没有按照您的要求执行。您正在使用 fopen 打开一个文件,但您没有以任何方式将它链接到 destinfd。您可能想改用 open,然后使用 dup2 将文件描述符移动到您想要的位置。

int redirect(char *filename, int flags, int destinfd)
{
    int newfd;

    if(flags == 0) {
        return -1;
    } else if(flags == 1) {
        newfd = open(filename, O_WRONLY);
        if (newfd == -1) {
            perror("open for write failed");
            return -1;
        }
    } else if(flags == 2) {
        newfd = open(filename, O_RDONLY);
        if (newfd == -1) {
            perror("open for read failed");
            return -1;
        }
    } else {
        return -1;
    }
    if (dup2(newfd, destinfd) == -1) {
        perror("dup2 failed");
        close(newfd);
        return -1;
    }
    close(newfd);
    return destinfd;
}