gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:12:33 25 4
gpt4 key购买 nike

我正在制作一个小 shell,但我的两个函数遇到一些问题。它们有点断章取义,但我希望您能理解我想要做什么,这样我就不必发布我的整个代码。

我的 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 是我要重定向的 std 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;
}

关于创建我自己的重定向和重复管道函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31457364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com