如何在 Rust 中将线程提升为子进程?

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

我需要写一些类似于compiletest的东西。 Compiletest 通过调用 rustc 进程并捕获 stdout/stderr 来工作。我的项目还没有 运行 的二进制文件,所以我需要另一种方法来创建子进程。

我无法使用通道或标准输出,因为它不受我的代码控制。

How can I promote a thread to child process

你不能。这只是操作系统不的事情;它不是 Rust 特有的。您不能启动任意线程,然后将其 ("promote it") 移动到另一个进程;线程和进程是截然不同的概念。

My project does not have a binary to run yet

我建议做一个。


如果您只想启动另一个进程,可以使用 std::process::Command。这将是最推荐的选项。

POSIX 确实有 fork 调用,它复制了进程的 entire 内存和 current 线程,所以理论上你可以使用它来 "promote" 当前线程到一个新进程。

Using this in a multithreaded context can be very complicated 并且默认情况下基本上总是建议反对。

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

另请参阅:

  • fork man page
  • fork in multi-threaded program
  • What is the closest thing windows has to fork()?

capturing stdout/stderr

隐藏的、不稳定的更改当前线程的方法 stdout / stderr。 Rust 的测试框架使用这些方法。如果您有兴趣使这些稳定,您也许可以 offer to help on the tracking issue.