[erlang-questions] tempfile, or O_EXCL

tsuraan tsuraan@REDACTED
Thu Feb 12 18:03:45 CET 2009


Since this posting is now google's top hit for erlang tempfile, I'll
self-reply with a port-based implementation of tempfile:mktemp.  It's
quick and dirty, but seems to work reasonably well, and I assume the
underlying unix mktemp program does use O_EXCL, so it should be
reasonably safe.  If anybody has any improvements, comments, etc, feel
free to post them.

-module(tempfile).
-export([mktemp/0, mktemp/1]).

mktemp() ->
  mktemp([{dir, "/var/tmp"}, {template, "tmp.XXXXXXXXXX"}]).

mktemp(Args) ->
  Cmd = process_args(Args, "mktemp"),
  Port = open_port({spawn, Cmd}, [{line, 1000},
                                  use_stdio,
                                  exit_status,
                                  stderr_to_stdout]),
  get_response(Port, nil).

process_args([], Cmd) -> Cmd;
process_args([{Flag, Value} | Rest], Cmd) ->
  case Flag of
    dir ->
      process_args(Rest, Cmd ++ " " ++ "--tmpdir=" ++ Value);
    template ->
      process_args(Rest, Cmd ++ " " ++ Value)
  end.

get_response(Port, Resp) ->
  case Resp of
    nil ->
      receive
        { Port, {data, {_, Line}}} ->
          get_response(Port, Line);
        { Port, {exit_status, _ }} ->
          { error, "No response from mktemp" }
      end;
    Resp ->
      receive
        { Port, {data, _}} ->
          get_response(Port, Resp);
        { Port, {exit_status, 0}} ->
          { ok, Resp };
        { Port, {exit_status, _}} ->
          { error, Resp }
      end
  end.


On 17/11/2008, tsuraan <tsuraan@REDACTED> wrote:
> Is there any way to specify exclusive (posix O_EXCL) with write when
> opening a file in Erlang?  I couldn't find a mkstemp anywhere in the
> standard library, so I wrote one myself, but without EXCL, it's not
> very safe.  I'd like to fix that, but I don't see how to do so without
> being able to open a file in exclusive write mode.
>



More information about the erlang-questions mailing list