重定向stdin stdout stderr
dup() dup2()都是用于重定向
dup函数的作用:复制一个现有的句柄,产生一个与“源句柄特性”完全一样的新句柄(也即生成一个新的句柄号,并关联到同一个设备)
dup2函数的作用:复制一个现有的句柄到另一个句柄上,目标句柄的特性与“源句柄特性”完全一样(也即首先关闭目标句柄,与设备断连
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char* argv[])
{
int fd;
{
int fd;
fd = open("my.file",O_WRONLY|O_CREAT);
if(fd == -1)
{
perror("/nERROR: fail to creat my.file.");
return -1;
}
if(dup2(fd,STDOUT_FILENO) == -1)
{
perror("/nERROR: fail to redirect std output.");
return -1;
}
if(
if(fd == -1)
{
perror("/nERROR: fail to creat my.file.");
return -1;
}
if(dup2(fd,STDOUT_FILENO) == -1)
{
perror("/nERROR: fail to redirect std output.");
return -1;
}
if(