Why does an atexit handler panic when it accesses stdout?
Asked Answered
G

1

5

The Rust program below panics when it accesses stdout in the atexit handler.

extern crate libc;

extern "C" fn bye() {
    println!("bye");
}

fn main() {
    println!("hello");
    unsafe { libc::atexit(bye) };
}

Output:

hello
thread '<main>' panicked at 'cannot access stdout during shutdown', ../src/libcore/option.rs:298
fatal runtime error: Could not unwind stack, error = 5
An unknown error occurred

It seems to me that this registration should run before our atexit registration, so this line in the handler should run only after our custom handler. Thus it should not panic.

Gymnastic answered 14/3, 2016 at 5:29 Comment(1)
I ran into the same problem, although my error code was pointer being freed was not allocated. When replacing println! with libc::printf it works though. I agree: it seems that the rust destruction runs too earlyPollinize
O
8

You're confusing libc::atexit, which you call, and sys_common::at_exit (in src/libstd/sys/common/mod.rs) which your link points to and which Rust calls during early cleanup.

Those are two different cleanup queues, and I wouldn't want to rely on them being executed in a specific order.

Ovation answered 14/3, 2016 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.