Skip to content

Add setsid method to CommandExt trait #184

Closed
@HarveyHunt

Description

@HarveyHunt

Proposal

Problem statement

Currently, if you want to use Command to spawn a new process and create a new session, then you need to use the pre_exec method. However, calling pre_exec means that the POSIX spawn fast path can't be used which makes spawning a new process more expensive than necessary.

By exposing the ability to pass the POSIX_SPAWN_SETSID flag to the POSIX spawn method it becomes possible to use the fast path to create processes. It also removes the need for unsafe code.

Motivation, use-cases

I don't have example code to share here, but I've been developing and maintaining a system that spawns multiple processes a second. These processes are started in new sessions to allow the main process to handle graceful shutdown upon receiving CTRL+C from the terminal.

Using the existing pre_exec method, the fork + exec required uses considerable kernel CPU. Switching to using the POSIX spawn fast path reduced the kernel CPU usage by ~60% IIRC.

Solution sketches

The std::os::unix::process::CommandExt trait can be updated to include a new setsid method, with the following signature:

trait CommandExt {
    fn setsid(&mut self) -> &mut Command
}

If a user calls .setsid() then the POSIX_SPAWN_SETSID flag will be passed to POSIX spawn.

A slightly different interface could have the following signature:

trait CommandExt {
    fn setsid(&mut self, setsid: bool) -> &mut Command
}

This would allow the caller to call setsid(false) to remove the setsid option from a Command that previously had it set. However, I'm not sure how useful this is in practice and it makes the method more verbose to use.

Links and related work

In my excitement to add this, I've done things in the wrong order and have submitted a PR and tracking issue already.

Rust PR: rust-lang/rust#105377
Rust Tracking issue: rust-lang/rust#105376

Man page for posix_spawn: https://man7.org/linux/man-pages/man3/posix_spawn.3.html

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions