我正在用C语言编写一个类的shell脚本,我让我的程序执行除文件重定向之外的所有命令。有人能帮我弄清楚文件重定向需要怎么做吗?我知道当fork返回0时我需要这样做,但我不确定该怎么做。
任何帮助都将不胜感激。
代码:这是我的代码的更新版本。创建文件很好,但是我不确定之后该做什么。我关闭了正确的文件描述符,然后将我的文件描述符复制到最低开放描述符。执行dup后,除了关闭正确的文件描述符之外,您还能帮助我做什么吗?
args[]是我存储输入的数组(例如ls -l,ls -l > out)
if ((cpid = fork()) == 0)
{
for ( i = 0; i < size; i++)
{
if ( *args[i] == '<' )
{
if ((fd = open(args[i+1], O_RDONLY)) == -1)
{
perror("open");
exit(2);
}
else
{
close(0);
dup(fd);
close(fd);
}
}
if ( *args[i] == '>' )
{
if ((fd = open(args[i+1], O_WRONLY | O_CREAT, 0644)) == -1)
{
perror("open");
exit(2);
}
else
{
close(1);
dup(fd);
close(fd);
}
}
}
execve(path,args,environ);
perror("execve");
exit(2);
}发布于 2012-03-08 03:57:49
查看dup函数here
https://stackoverflow.com/questions/9608111
复制相似问题