![](/img/trans.png)
[英]Problem when redirecting standard output with dup and dup2 in c
[英]dup2() is preventing output
我的代码粘贴在下面。
我正在尝试使用dup2将我的输出重定向到文件。
如果我使用它重定向,则可以正常工作(如果删除注释),则在文件中而不是在stdout上输出。 例如:ls> test,导致ls输出到test。
问题是ls,不带>不会输出任何内容。 如果我保留注释ls输出的原样,尽管没有重定向的能力。
redirect [0]是<或>,或者没有任何内容redirect [1]是文件重定向到的路径
命令是由cstring组成的数组,带有命令的图片
带有代码注释的示例输出
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1> ls
a.out myshell.c myshell.c~
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1>
代码未注释
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1> ls
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1>
/*
if (!strcmp(redirect[0],">")){
if ((fd = open(redirect[1], O_RDWR | O_CREAT)) != -1)
dup2(fd, STDOUT_FILENO);
close(fd);
}
*/
if (command[0][0] == '/'){
int c = execv(command[0], commands);
if (c != 0){
printf("ERROR: command does not exist at path specified\n");
exit(0);
}
}
else if (!execv(path, commands)){
exit(0);
}
这段代码有效,重定向到file.out
:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *redirect[] = { ">", "file.out" };
char *command[] = { "/bin/ls", "-l", 0 };
if (!strcmp(redirect[0], ">"))
{
if ((fd = open(redirect[1], O_WRONLY | O_CREAT, 0644)) != -1)
{
fprintf(stderr, "Dupping stdout to %s\n", redirect[1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (command[0][0] == '/')
{
execv(command[0], command);
fprintf(stderr, "ERROR: command %s does not exist at path specified\n", command[0]);
return(1);
}
else
{
fprintf(stderr, "ERROR: not handling relative names like %s\n", command[0]);
return(1);
}
return 0;
}
此代码也可以工作,而不重定向到文件:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *redirect[] = { "<", "file.in" };
char *command[] = { "/bin/ls", "-l", 0 };
if (!strcmp(redirect[0], ">"))
{
if ((fd = open(redirect[1], O_WRONLY | O_CREAT, 0644)) != -1)
{
fprintf(stderr, "Dupping stdout to %s\n", redirect[1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (command[0][0] == '/')
{
execv(command[0], command);
fprintf(stderr, "ERROR: command %s does not exist at path specified\n", command[0]);
return(1);
}
else
{
fprintf(stderr, "ERROR: not handling relative names like %s\n", command[0]);
return(1);
}
return 0;
}
注意,它设置command
数组并使用execv(command[0], command);
-这是推荐的经商方式。 您的代码似乎有一个可变commands
,可能带有程序的参数。 您似乎也有一个可变path
,大概是程序的路径名。 由于我们看不到其中的内容,因此很难知道其中包含的内容以及可能存在问题的位置。 请注意command
数组末尾的显式空指针( 0
)。 那很关键。 还要注意,错误消息指出了失败的原因。 没有什么比不说“它”是什么的程序说“它出错了”更令人沮丧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.