【发布时间】:2019-10-08 02:28:49
【问题描述】:
我对获取在 Rust 程序中创建的线程的 PID 很感兴趣。如documentation 中所述,thread::id() 不适用于此目的。我发现Get the current thread id and process id as integers? 似乎是答案,但我的实验表明它不起作用。
这是代码:
extern crate rand;
extern crate libc;
use std::thread::{self, Builder};
use std::process::{self, Command};
use rand::thread_rng;
use rand::RngCore;
use std::time::Duration;
use std::os::unix::thread::JoinHandleExt;
use libc::pthread_t;
fn main() {
let main_pid = process::id();
println!("This PID {}", main_pid);
let b = Builder::new().name(String::from("LongRunningThread")).spawn(move || {
let mut rng = thread_rng();
let spawned_pid = process::id();
println!("Spawned PID {}", spawned_pid);
loop {
let u = rng.next_u64() % 1000;
println!("Processing request {}", u);
thread::sleep(Duration::from_millis(u));
}
}).expect("Could not spawn worker thread");
let p_threadid : pthread_t = b.as_pthread_t();
println!("Spawned p_threadid {}", p_threadid);
let thread_id = b.thread().id();
println!("Spawned thread_id {:?}", thread_id);
thread::sleep(Duration::from_millis(60_000));
}
在 Linux 机器上运行程序的输出如下:
This PID 8597
Spawned p_threadid 139858455706368. <-- Clearly wrong
Spawned thread_id ThreadId(1) <-- Clearly wrong
Spawned PID 8597
Processing request 289
Processing request 476
Processing request 361
Processing request 567
以下是我系统中 htop 输出的摘录:
6164 1026 root 20 0 98M 7512 6512 S 0.0 0.0 0:00.03 │ ├─ sshd: dash [priv]
6195 6164 dash 20 0 98M 4176 3176 S 0.0 0.0 0:00.20 │ │ └─ sshd: dash@pts/11
6196 6195 dash 20 0 22964 5648 3408 S 0.0 0.0 0:00.09 │ │ └─ -bash
8597 6196 dash 20 0 2544 4 0 S 0.0 0.0 0:00.00 │ │ └─ ./process_priorities
8598 6196 dash 20 0 2544 4 0 S 0.0 0.0 0:00.00 │ │ └─ LongRunningThre
我想从衍生线程获得的 PID 是 8598,但我不知道如何在 Rust 程序中获取它。有什么想法吗?
【问题讨论】:
-
链接的答案显示了如何获取 pthread ID。我已经更新了这个问题,另一个答案清楚地说明了 pthread vs OS(特别是 Linux)ID(htop 报告的内容)。
-
该死。所以你告诉我 pthread_id 是另一个需要映射到 OS PID 的中间 id?关于如何从中获取 PID 的任何建议?
-
我不确定。我会尝试
gettid。
标签: linux multithreading rust operating-system