2010-04-26 49 views

回答

0

如果你真的在編程Linux內核,那麼你會看到連接到你有興趣在這個過程中的task_structfiles_struct

但我想你的意思是你'使用內核API編寫用戶空間程序以在 Linux上運行。在這種情況下,這有點困難。

沒有直接的方式來做到這一點,我知道。但是,您應該可以使用fcntl做一點小事。基本上,您可以查詢文件描述符的狀態標誌,並且如果出現錯誤(或多或少),則說明文件描述符無效 - 因此可用。

但是,如果你有多個線程它是活潑的。另一個線程可以在檢查完文件後使用文件描述符。如果你真的想要使用該文件描述符,可能需要dup2()F_DUPFD,但我不確定你實際上想要做什麼。

示例代碼:

#include <stdio.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <errno.h> 

int main(void) 
{ 
    int rc, fd; 

    for (fd = 0; fd < 8; fd++) { 
     errno = 0; 
     rc = fcntl(fd, F_GETFL); 

     if (rc >= 0) 
      printf("fd %d is open\n", fd); 
     else if (errno == EBADF) 
      printf("fd %d is closed\n", fd); 
     else 
      printf("error %d querying fd %d \n", errno, fd); 
    } 

    return 0; 
} 
2

是的,你可以測試:

struct files_struct * files = task->files; 
struct fdtable *fdt; 

spin_lock(&files->file_lock); 

fdt = files_fdtable(files); 
if (test_bit(fd, fdt->open_fds->fds_bits)) 
{ 
    /* fd is in use */ 
} 

spin_unlock(&files->file_lock); 

然而,信息是可能過時,只要你解開files結構,所以,真正的問題你會用它做什麼?

+0

+1最後一句。 – 2011-02-11 23:53:55

1

假設你是在內核和有結構的task_struct * PROC進程上下文,你只需要檢查給FD對應於這一過程中打開文件,而不是實際使用莫名其妙的文件:

int is_valid_fd_for_process(int fd, struct task_struct* proc) 
{ 
    int exists; 

    rcu_read_lock(); 
    exists = (NULL != fcheck_files(proc->files, fd)); 
    rcu_read_unlock(); 

    return exists; 
} 

如果你真的想使用文件結構,這個FD地址或以後存儲它,你應該獲得它的參考。請參閱fget的代碼,它可以爲當前進程做到這一點,並將其適用於任何進程。

相關問題