PrevUpHomeNext

POSIX specifics

Binding file descriptors
Closing file descriptors
Arbitrary extensions

Use bind_fd to bind any file descriptor (not only a standard stream):

file_descriptor_sink sink("output.txt");
execute(
    run_exe("test"),
    bind_fd(4, sink)
);

Use close_fd to close a single file descriptor:

execute(
    run_exe("test"),
    close_fd(STDIN_FILENO)
);

Use close_fds to close multiple file descriptors:

execute(
    run_exe("test"),
    close_fds(boost::assign::list_of(STDIN_FILENO)(4))
);

Use close_fds_if to close all file descriptors a predicate returns true for:

execute(
    run_exe("test"),
    close_fds_if([](int fd){ return fd == STDIN_FILENO; })
);

On POSIX executor calls fork and execve to start a program. Boost.Process provides five generic initializers to run any code before fork is called, afterwards if fork failed or succeeded, before execve is called and afterwards if execve failed: on_fork_setup, on_fork_error, on_fork_success, on_exec_setup and on_exec_error. These initializers can be used to arbitrarily extend Boost.Process:

const char *env[2] = { 0 };
env[0] = "LANG=de";
execute(
    run_exe("test"),
    on_fork_setup([env](executor &e)
        { e.env = const_cast<char**>(env); }),
    on_fork_error([](executor&)
        { std::cerr << errno << std::endl; }),
    on_exec_setup([](executor&)
        { chroot("/new/root/directory/"); }),
    on_exec_error([](executor&)
        { std::ofstream ofs("log.txt"); if (ofs) ofs << errno; })
);

The example sets the environment variable LANG to de. If fork fails, the system error is written to the standard error stream. If fork doesn't fail, chroot is called. This happens in the newly created (forked) process before execve is called. If execve fails, the system error is written to a file.

[Note] Note

Boost.Process guarantees to call initializers in the order they are passed to execute. The order is important if several initializers try to set the same member variables in the executor. The initializers provided by Boost.Process have been designed to work correctly no matter which order they are used in. You only have to be careful if you use the generic initializers on_fork_setup, on_fork_error, on_fork_success, on_exec_setup and on_exec_error.


PrevUpHomeNext