小研究一下dup()函数
时间:2006-11-11 来源:longtem
手册:
#include <unistd.h>
int dup(int fildes);
int dup2(int fildes, int fildes2);
dup, dup2 - duplicate an open file descriptor
RETURN VALUE
Upon successful completion a non-negative integer, namely the file
descriptor, shall be returned; otherwise, -1 shall be returned and
errno set to indicate the error.
其实,dup可用dup2取代,方式:
fda=dup(fdb) <=>dup2(fdb,fda)
所以以下的讨论只用dup2()
实验用的函数:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#define PTHA "/dev/shm/testa"
#define PTHB "/dev/shm/testb"
int main()
{
int fda,fdb;
int fdtmp; //to save fdb
fdb=open(PTHB,O_CREAT | O_RDWR,0666);
fda=open(PTHA,O_CREAT | O_RDWR,0666);
dup2(fdb,fdtmp);
dup2(fda,fdb); //make fdb=fda
write(fda,"throute fda",11);//all goes to fda
write(fdb,"throute fdb",11);//all goes to fda
dup2(fdtmp,fdb);//restore
write(fdb,"after invoke",12);//all goes to fdb now
return 0;
}
功能利用,输出重定向:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#define PTHA "/dev/shm/testa"
int main()
{
int fda;
fda=open(PTHA,O_CREAT | O_RDWR,0666);
dup2(fda,STDOUT_FILENO); //re-direct stdout
system("ls");
close(fda);
return 0;
}
执行完生成的程序后,会发现/dev/shm/testa里含有ls命令的输出
#include <unistd.h>
int dup(int fildes);
int dup2(int fildes, int fildes2);
dup, dup2 - duplicate an open file descriptor
RETURN VALUE
Upon successful completion a non-negative integer, namely the file
descriptor, shall be returned; otherwise, -1 shall be returned and
errno set to indicate the error.
其实,dup可用dup2取代,方式:
fda=dup(fdb) <=>dup2(fdb,fda)
所以以下的讨论只用dup2()
实验用的函数:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#define PTHA "/dev/shm/testa"
#define PTHB "/dev/shm/testb"
int main()
{
int fda,fdb;
int fdtmp; //to save fdb
fdb=open(PTHB,O_CREAT | O_RDWR,0666);
fda=open(PTHA,O_CREAT | O_RDWR,0666);
dup2(fdb,fdtmp);
dup2(fda,fdb); //make fdb=fda
write(fda,"throute fda",11);//all goes to fda
write(fdb,"throute fdb",11);//all goes to fda
dup2(fdtmp,fdb);//restore
write(fdb,"after invoke",12);//all goes to fdb now
return 0;
}
功能利用,输出重定向:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#define PTHA "/dev/shm/testa"
int main()
{
int fda;
fda=open(PTHA,O_CREAT | O_RDWR,0666);
dup2(fda,STDOUT_FILENO); //re-direct stdout
system("ls");
close(fda);
return 0;
}
执行完生成的程序后,会发现/dev/shm/testa里含有ls命令的输出
相关阅读 更多 +