检查可执行文件是否有效

时间:2017-01-17 02:10:16

标签: unix operating-system ocaml

假设我想在使用其参数调用它之前检查某个可执行文件foo是否有效。可以从命令行获得各种方法(例如,$> hash foo)。

但是,据我所知,OCaml的SysUnix模块都没有提供此类功能。

如何定义一个接受指示unix可执行文件的字符串的机制,并返回一个指示参数是否可执行的bool?

4 个答案:

答案 0 :(得分:5)

允许您检查文件是否可执行的函数是Unix.access。如果您想要另外搜索路径,则需要额外的脚手架,例如:

let syspath = String.split_on_char ':' (Sys.getenv "PATH")

let check_executable path =
  let open Unix in
  try
    access path [ X_OK ]; Some path
  with _ -> None

let starts_with s prefix =
  let open String in
  let plen = length prefix in
  length s >= plen && sub s 0 plen = prefix

let search_path name =
  if starts_with name "/" || starts_with name "./" || starts_with name "../"
  then
    check_executable name
  else
    List.fold_left (fun acc dir ->
      match acc with
      | Some file -> Some file
      | None ->
        check_executable (Filename.concat dir name)
    ) None syspath

let main () =
  Array.iter (fun arg ->
    match search_path arg with
    | None -> Printf.printf "%s (Not found)\n" arg
    | Some file -> Printf.printf "%s -> %s\n" arg file)
  Array.(sub Sys.argv 1 (length Sys.argv - 1))

let () = main ()

答案 1 :(得分:2)

您可以使用file命令来实现此目的。 file为可执行文件返回此内容:

file /bin/ls

output => ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0x37cdd635587f519989044055623abff939002027, stripped

您可以解析输出或使用file命令具有的许多命令行选项之一。

答案 2 :(得分:2)

除了codeforester使用file的答案之外,还有对libmagic的绑定,它可以有效地让您访问file的输出而无需外壳。请参阅https://github.com/Chris00/ocaml-magic,opam中提供magic

答案 3 :(得分:2)

要检查文件是否可执行,我会使用该文件的权限 - 您可以通过以下方式获取它们:

 let getstat f = (Unix.stat (Filename.basename f)).Unix.st_perm;;
 Printf.printf "%d\n" (getstat ".bashrc");;
 > 644

显示已设置x标志。