Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an atexit handler panic when it accesses stdout?

Tags:

rust

atexit

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.

like image 1000
WiSaGaN Avatar asked Mar 14 '16 05:03

WiSaGaN


1 Answers

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.

like image 180
Sebastian Redl Avatar answered Nov 15 '22 08:11

Sebastian Redl