日期:2014-05-16  浏览次数:20762 次

dup函数重定向时遇到问题
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
        int fd2;
        fd2 = open("lsttic.out",O_RDONLY|O_RDONLY|O_CREAT,777);
        if(dup2(fd2,1)==-1)
        {
                printf("dup error!!!");
                exit(0);
        }
        printf("hello world!!!\n");
        close(fd2);
        printf("hello world!!!\n");
        return 0;
}

为什么两个hello world 都既没有输出在终端上,也没有输出到文件里面?

------解决方案--------------------
O_RDONLY
------解决方案--------------------
O_RDONLY
------解决方案--------------------
O_CREAT,

两个只读?
------解决方案--------------------
改成读写后是可以的。不过第三个参数改成 0777 更好点。
------解决方案--------------------
错误两点:
777对应的权限为1411,这个权限明显错误了. 应该用八进制表示0777,或者用S_IWUSR等这样的或
open时的mod错误,,你想要输出的,当然得用写的O_WRONLY或者O_RDWR...

把原来的lsttic.out删除...然后试下面的.
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include <stdlib.h>
int main()
{
        int fd2;
        fd2 = open("lsttic.out",O_WRONLY 
------解决方案--------------------
 O_CREAT, 0777);
if(fd2 < 0) {
perror("open error");
exit(-1);
}
        if(dup2(fd2,1)==-1)
        {
                perror("dup error!!!");
                exit(0);
        }
        printf("hello world!!!\n");
        close(fd2);
        printf("hello world!!!\n");
        return 0;
}

------解决方案--------------------
引用:
那怎样才能取消重定向呢?

给你看个例子吧,,
#include<stdio.h>
#include <string.h>
#include<unistd.h>
#include<fcntl.h>
#include <stdlib.h>
#include <string.h>


#define MSG "HAHAHA\n"
int main()
{
int fd;
printf("ttyname is:%s\n", ttyname(0));
printf("ttyname is:%s\n", ttyname(1));
if((fd = open(ttyname(0), O_WRONLY)) < 0) {
perror("open error");
return -1;
}
printf("new fd is %d\n", fd);