linux 下关闭标准输入、输出再打开

779阅读 0评论2008-08-28 iceway_cu
分类:LINUX

在linux下,关闭stdin,stdout,stderr后重新打开的方法:先用dup2(...)函数复制stdin,stdout,stderr文件描述符,然后复制回去。代码示例:
 

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
     //this integer variable must be a value between 0 to 255

    int fd = 100

    dup2( 1, fd );
    printf("copy 1 to fd\n");

    //close standard output
    close(1);
    printf("close 1\n");

    //reopen standard output
    dup2(fd, 1);
    printf("cope fd to 1\n");
    return 0;
}

 

输出结果:

copy 1 to fd
copy fd to 1

因为标准输出被close所以close 1没有被输出。

 

 

上一篇:关于linux内核的ioctl函数
下一篇:pipe函数使用