linux文件句柄的作用,如果指向的文件被移动,Linux上的打开文件句柄会发生什么?...

在/ proc /目录下,您将找到当前处于活动状态的每个进程的列表,只需找到您的PID并且所有数据都在那里。 有趣的信息是文件夹fd /,您将找到该进程当前打开的所有文件处理程序。

最终你会找到一个指向你的设备的符号链接(在/ dev /或甚至/ proc / bus / usb /下),如果设备挂起链接将会死,并且无法刷新此句柄,该过程必须关闭并且 再次打开它(即使重新连接)

此代码可以读取PID的链接当前状态

#include

#include

#include

int main() {

// the directory we are going to open

DIR *d;

// max length of strings

int maxpathlength=256;

// the buffer for the full path

char path[maxpathlength];

// /proc/PID/fs contains the list of the open file descriptors among the respective filenames

sprintf(path,"/proc/%i/fd/",getpid() );

printf("List of %s:\n",path);

struct dirent *dir;

d = opendir(path);

if (d) {

//loop for each file inside d

while ((dir = readdir(d)) != NULL) {

//let's check if it is a symbolic link

if (dir->d_type == DT_LNK) {

const int maxlength = 256;

//string returned by readlink()

char hardfile[maxlength];

//string length returned by readlink()

int len;

//tempath will contain the current filename among the fullpath

char tempath[maxlength];

sprintf(tempath,"%s%s",path,dir->d_name);

if ((len=readlink(tempath,hardfile,maxlength-1))!=-1) {

hardfile[len]='\0';

printf("%s -> %s\n", dir->d_name,hardfile);

} else

printf("error when executing readlink() on %s\n",tempath);

}

}

closedir(d);

}

return 0;

}

这个最终代码很简单,你可以使用linkat函数。

int

open_dir(char * path)

{

int fd;

path = strdup(path);

*strrchr(path, '/') = '\0';

fd = open(path, O_RDONLY | O_DIRECTORY);

free(path);

return fd;

}

int

main(int argc, char * argv[])

{

int odir, ndir;

char * ofile, * nfile;

int status;

if (argc != 3)

return 1;

odir = open_dir(argv[1]);

ofile = strrchr(argv[1], '/') + 1;

ndir = open_dir(argv[2]);

nfile = strrchr(argv[2], '/') + 1;

status = linkat(odir, ofile, ndir, nfile, AT_SYMLINK_FOLLOW);

if (status) {

perror("linkat failed");

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值