Search code examples
processruststderr

How can I promote a thread to child process in Rust?


I need to write something similar to compiletest. Compiletest works by invoking the rustc process and capturing stdout/stderr. My project does not have a binary to run yet, so I need another way to create a subprocess.

I can't use a channel nor stdout because it's not controlled by my code.


Solution

  • How can I promote a thread to child process

    You cannot. This is simply something that operating systems don't do; it's not specific to Rust. You cannot start an arbitrary thread and then move it ("promote it") to another process later; threads and processes are very different concepts.

    My project does not have a binary to run yet

    I suggest making one.


    If you wish to simply start another process, you can use std::process::Command for that. This would be the most recommended option.

    POSIX does have the fork call, which duplicates the entire memory of the process and the current thread, so theoretically you could use this to "promote" the current thread to a new process.

    Using this in a multithreaded context can be very complicated and basically will always be recommended against by default.

    Support for fork on Windows is... limited, at best. If you only care about POSIX systems, you can use fork from the libc crate.

    See also:


    capturing stdout/stderr

    There are hidden, unstable methods for changing the current threads stdout / stderr. Rust's testing framework uses these methods. If you'd be interested in making these stable, you could perhaps offer to help on the tracking issue.