# tmux_scope:run/2

- **Package:** libtmux_erlang
- **Language:** Erlang
- **Kind:** function
- **Source:** https://github.com/libtmux/libtmux-erlang/blob/d1b6308440cf9eb8f6647e7ae434bce60e849368/apps/libtmux_erlang/src/tmux_scope.erl#L61
- **Page:** https://libtmux.org/en/erlang/latest/reference/tmux_scope-run-2/

```
run(Function, Cleanup)
-spec run(fun(() -> Value),
          fun(() -> ok | {error, term()})) ->
             {ok, Value} | {error, failure()}.
```

Run a callback, then attempt cleanup once, synchronously in the calling process. This function performs only the I/O supplied by those functions. The callback has no library duration timer. Abrupt uncatchable caller death remains subject to each resource's existing ownership policy.

Only ok proves cleanup success. Normalize resource-specific successful replies
inside the cleanup function. With successful cleanup, return {ok, Value} or
re-raise the original callback exception with its reason and stack. A callback
returning an error tuple is an ordinary value. Cleanup failure instead returns
{error, Failure} with `t:failure/0`, preserving both outcomes. An unexpected
cleanup return is recorded as invalid_cleanup_result.

Handle an inner scope's error explicitly when nesting scopes. Otherwise it is
an ordinary outer callback value. Keep resource handles for recovery; this
function does not infer ownership or retry cleanup.

## Examples

```erlang
1> tmux_scope:run(fun() -> done end, fun() -> ok end).
{ok,done}
2> tmux_scope:run(fun() -> done end, fun() -> {error, enoent} end).
{error,#{code => scope_cleanup_failed,
         primary => {ok,done},cleanup => {error,enoent}}}
3> Work = fun() -> error(build_failed) end, ok.
ok
4> {error, F} = tmux_scope:run(Work, fun() -> {error, busy} end), ok.
ok
5> {exception, error, build_failed, [_ | _]} = maps:get(primary, F), ok.
ok
6> maps:get(cleanup, F).
{error,busy}
```

## Parameters

- `Function` (`fun(() -> Value)`)
- `Cleanup` (`fun(() -> ok | {error, term()})`)

## Guides

Pages that discuss `run/2`.

- [Ownership and identity](/en/erlang/latest/topics/ownership/)
