最近看框架的源碼,總是遇到os.dup2這個函數,不是很能理解它的用法,于是去看了python的源碼,Dup2.c:
/*
* Public domain dup2() lookalike
* by Curtis Jackson @ AT&T Technologies, Burlington, NC
* electronic address: burl!rcj
*
* dup2 performs the following functions:
*
* Check to make sure that fd1 is a valid open file descriptor.
* Check to see if fd2 is already open; if so, close it.
* Duplicate fd1 onto fd2; checking to make sure fd2 is a valid fd.
* Return fd2 if all went well; return BADEXIT otherwise.
*/
#include <fcntl.h>
#include <unistd.h>
#define BADEXIT -1
int
dup2(int fd1, int fd2)
{
if (fd1 != fd2) {
if (fcntl(fd1, F_GETFL) < 0)
return BADEXIT;
if (fcntl(fd2, F_GETFL) >= 0)
close(fd2);
if (fcntl(fd1, F_DUPFD, fd2) < 0)
return BADEXIT;
}
return fd2;
}
從源碼上看,dup2傳入兩個文件描述符,fd1和fd2(fd1是必須存在的),如果fd2存在,就關閉fd2,然后將fd1代表的那個文件(可以想象成是P_fd1指針)強行復制給fd2,fd2這個文件描述符不會發生變化,但是fd2指向的文件就變成了fd1指向的文件。
這個函數最大的作用是重定向,參考下面的python代碼:
import os
#打開一個文件
f=open('txt','a')
#將這個文件描述符代表的文件,傳遞給1描述符指向的文件(也就是stdout)
os.dup2(f.fileno(),1)
f.close()
#print輸出到標準輸出流,就是文件描述符1
print 'line1'
print 'line2'
#腳本執行結果:
#生成一個txt文件,內容是:
#line1
#line2