我正在嘗試檢測特定位置 (myPath) 中的打開檔案夾。我正在使用 strstr() 但我看到我的系統在執行此函式后總是崩潰(圖片)。如果我洗掉檢查 (if(ret)),它會正常作業這是我的代碼:
struct task_struct *task_list;
struct fdtable * fdt = NULL;
unsigned int process_count = 0;
struct path files_path;
char *access_mode;
char *cwd;
int res;
char *myPath = "/home/anh/src/";
char *buf = (char *)kmalloc(GFP_KERNEL,100*sizeof(char));
char * ret;
for_each_process(task_list) {
fdt = files_fdtable(task_list->files);
int i=0;
while(fdt->fd[i] != NULL) {
files_path = fdt->fd[i]->f_path;
cwd = d_path(&files_path,buf,100*sizeof(char));
if(cwd){//Check if cwd != NULL
ret = strstr(cwd, myPath);//check seeked file path and myPath
if(ret)
{
printk(KERN_INFO "Open file with fd %d cwd: %s", i,cwd);
}
}
i ;
}
process_count ;
}
有人可以審查并支持我解決這個問題嗎?為什么不能在 Linux 內核模塊中使用 strstr() 或者有其他方法來驗證字串是否在字串中?
最好的問候,安
uj5u.com熱心網友回復:
一個合理的解釋是發生了錯誤,因此cwd不是有效的指標。strstr在此無效指標上呼叫并崩潰。如果沒有if(ret),strstr呼叫會被優化掉,所以不會發生崩潰。
Linux 內核中的函式通常會在出錯時回傳錯誤代碼。的檔案d_path特別指出是這種情況。
如果路徑太長,則回傳指向緩沖區的指標或錯誤代碼。
if (cwd)檢查cwd非空。如果cwd包含錯誤代碼,則為非空。所以if (cwd)不是一個有用的檢查。回傳指標的函式的正確錯誤檢查是IS_ERR().
cwd = d_path(&files_path,buf,100*sizeof(char));
if (IS_ERR(cwd)) {
printk(KERN_WARN "At i=%d: d_path -> %ld", i, PTR_ERR(cwd));
} else {
ret = strstr(cwd, myPath);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336476.html
上一篇:我如何使用指標作為引數
