2011-04-19 120 views
2

所以我有一個文件路徑。如何檢查它是否可執行? (UNIX,C++)有文件路徑如何檢查它是否可執行?

+0

「可執行文件」,這對您意味着什麼?例如。 Python腳本文件(與#!/ usr/bin/python一樣的shebang)? – 2011-04-19 16:41:24

+0

你以前的帖子有重複嗎? http://stackoverflow.com/questions/5719438/how-to-find-out-if-path-leads-to-executable-file – Void 2011-04-19 16:56:32

回答

7

檢查的權限(狀態)位。

#include <sys/stat.h> 

bool can_exec(const char *file) 
{ 
    struct stat st; 

    if (stat(file, &st) < 0) 
     return false; 
    if ((st.st_mode & S_IEXEC) != 0) 
     return true; 
    return false; 
} 
+2

但這個答案「可以*某人*執行文件?」不是「可以*我*執行文件嗎?」也許OP應該考慮[access(2)](http://linux.die.net/man/2/access)。 – 2011-04-19 16:52:18

+0

這將在mac os x上運行嗎? – Rella 2011-04-19 23:12:05

+0

@Blender - 是的。 – 2011-04-20 13:57:57

5

訪問(2):

#include <unistd.h> 

if (! access (path_name, X_OK)) 
    // executable 

呼叫至STAT(2)具有更高的開銷填寫該結構。除非你需要額外的信息。

+1

這可能是比我更好的解決方案;我忘記了access()'。 – 2011-04-19 17:01:39

+1

你是說access()不是自己做一個stat()和getpid(),getuid(),getgid()?我會想象,開銷幾乎是相同的。 – 2014-06-09 00:13:48

+0

access()的實現是未知的。但這不是我所說的 - 填寫一個統計結構是有代價的。 – 2014-06-18 21:06:07

1

考慮使用access(2),檢查用於相對於當前處理的uid權限和GID:

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

int can_exec(const char *file) 
{ 
    return !access(file, X_OK); 
} 

int main(int ac, char **av) { 
    while(av++,--ac) { 
     printf("%s: %s executable\n", *av, can_exec(*av)?"IS":"IS NOT"); 
    } 
} 
+0

這將在mac os x上工作嗎? – Rella 2011-04-19 23:11:35

+0

@Blender - 根據[developer.apple.com](http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/access.2.html),是的,這將在Mac OS X上工作。 – 2011-04-20 13:53:15

4

有一個在人頁的底部一個警告以進行訪問(2):

CAVEAT Access()是一個潛在的安全漏洞,不應該被使用。

請記住,在調用access()與路徑字符串的時間與嘗試執行由路徑字符串引用的文件的時間之間存在爭用條件,文件系統可能會更改。如果這種競爭條件是一個問題,首先用open()打開文件並使用fstat()來檢查權限。

+0

我不確定open()/ fstat()會關閉手冊頁描述的爭用條件。比賽是,在OP的情況下,該文件可以改變它在access()和execv()之間的可執行性。隨着你的解決方案,它仍然可以在fstat()和execv()之間切換。我認爲手冊頁作者的意圖是你應該繼續並調用execv() - 如果它失敗了,那麼你有你的答案。 – 2011-04-20 13:56:43

相關問題