```std``` global state in shared libraries

Hello everyone!

Recently, I've made an experiment, creating two shared libraries in Rust (on Linux), one of which had a function that called fill_buf() on std::io::stdin().lock() object and printed it to stdout, and the other read (consumed) one byte from it and returned it. I've found something strange -- when called from a C application, the first library function read and printed a chunk of file and the second library function read a byte after that chunk. Calling the first function printed the previously-read buffer without any changes, as if two libraries had separate global states. When these libraries were used from Rust application, the app itself seemed to have its own global state that weren't used by libraries. Just wanted to note it, that shared libraries (like PAM modules) need to be careful to use unbuffered stdin reading (because the unconsumed buffer content may become inaccessible if the library is never called again) and stdout/stderr writing, or use stdio (however, it should be done carefully, because streams may be wide-oriented or -- for some implementations -- in text mode). As far as I understand, it also means that it's not safe to allocate and then Box::leak() in one shared library and get the Box in another (or the main app), so shared libraries should either provide C API constructors/destructors for such allocations (like fopen()/fclose() in stdio), or use special Box types (like one in stabby, which stores a pointer to the allocator with the allocated memory area).

yes, the stdin() function returns a static variable, which is a Mutex synchronized BufRead, here;

the rust standard library is its own abstraction (over the standard file descriptor in the kernel), similar to the stdin stream in the C standard library.

if you want to use the stdin file descriptor, use [from_raw_fd()](File in std::fs - Rust), for example:

let my_stdin = ManuallyDrop::new(FIle::from_raw_fd(0))

btw, rust StdIn, unlike C++ std::cin, is independent of the stdin stream in the C standard library, which also uses static states, e.g. if you managed to link 2 copies of glibc into your program, you'll observe similar behavior. see: