【发布时间】:2021-12-19 15:45:28
【问题描述】:
我想在发送SIGUSR1 信号时调用impl 方法。
考虑以下示例:
use libc::SIGUSR1;
use std::{thread, time};
struct Foo {
}
impl Foo {
fn show(&self) {
println!("Foo SIGNAL")
}
}
fn main() {
let foo = Foo {};
unsafe {
libc::signal(SIGUSR1, foo.show as usize);
}
loop{
println!("sleeping for 1 sec");
thread::sleep(time::Duration::from_secs(1));
}
}
我收到以下错误:
$ cargo run
Compiling hello_world v0.1.0 (/home/vasco/a)
error[E0615]: attempted to take value of method `show` on type `Foo`
--> src/main.rs:17:35
|
17 | libc::signal(SIGUSR1, foo.show as usize);
| ^^^^ method, not a field
|
help: use parentheses to call the method
|
17 | libc::signal(SIGUSR1, foo.show() as usize);
| ^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0615`.
error: could not compile `hello_world`
To learn more, run the command again with --verbose.
如果我听从建议 (libc::signal(SIGUSR1, foo.show() as usize);):
$ cargo run
Compiling hello_world v0.1.0 (/home/vasco/a)
error[E0605]: non-primitive cast: `()` as `usize`
--> src/main.rs:17:31
|
17 | libc::signal(SIGUSR1, foo.show() as usize);
| ^^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
error: aborting due to previous error
For more information about this error, try `rustc --explain E0605`.
error: could not compile `hello_world`
To learn more, run the command again with --verbose.
使用普通函数按预期工作:
use libc::SIGUSR1;
use std::{thread, time};
fn show() {
println!("Foo SIGNAL")
}
fn main() {
unsafe {
libc::signal(SIGUSR1, show as usize);
}
let delay = time::Duration::from_secs(1);
loop{
println!("sleeping for 1 sec");
thread::sleep(delay);
}
}
有什么建议吗?
谢谢
【问题讨论】:
-
这是不可能的,因为the underlying C function does not allow passing parameters to the signal handler,所以没有办法将
foo传递给处理程序。 -
我可以使用不同的板条箱吗?谢谢