Dưới thư mục/proc/bạn sẽ tìm thấy danh sách của mọi quá trình hiện đang hoạt động, chỉ cần tìm PID của bạn và tất cả dữ liệu liên quan là có. Một thông tin liên tục là thư mục fd /, bạn sẽ tìm thấy tất cả các trình xử lý tệp hiện đang được mở bởi quy trình.
Cuối cùng, bạn sẽ tìm thấy một liên kết tượng trưng cho thiết bị của bạn (dưới/dev/hoặc thậm chí/proc/bus/usb /), nếu thiết bị treo liên kết sẽ chết và sẽ không thể làm mới xử lý này, quá trình phải đóng và mở lại (ngay cả với kết nối lại)
mã này có thể đọc liên kết hiện trạng của PID của bạn
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
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;
}
mã cuối cùng này rất đơn giản, bạn có thể chơi với chức năng 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;
}
Tôi cho rằng điểm thứ hai của bạn được áp dụng như nhau nếu thư mục chứa tệp bị xóa. Là vậy sao? –
Tôi quan tâm đến một điều: nếu bạn sử dụng lệnh cp để ghi đè lên một tệp, đó có phải là trường hợp đầu tiên hoặc trường hợp thứ hai không? – xuhdev