Description
(The r# in the title is a joke.)
The first is my environment.
toolchain version:rustc 1.58.0 (02072b4 2022-01-11)
IDE name and version:CLion 2022.1 Build #CL-221.5080.224, built on April 14, 2022
Operating system:win 10
Then look at the sample code below.
main.rs
use std::env::current_exe;
use std::fs::File;
use std::io::Write;
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::thread::current;
use encoding::all::GBK;
use encoding::{EncoderTrap, Encoding};
fn main() {
let mut file = File::create(r"c:\copy.bat").unwrap();
let cmd = format!(r"copy {} c:\copy_result.exe", ¤t_exe().unwrap().to_str().unwrap());
let bytes = GBK.encode(cmd.as_str(), EncoderTrap::Strict).unwrap();
file.write(bytes.as_ref());
file.flush();
Command::new("cmd")
.creation_flags(0x08000000)
// .creation_flags(0x00000010)
.arg("/c")
.arg(r"c:\copy.bat")
.spawn();
}
[package]
name = "cmd_test"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
encoding = "0.2.33"
Running this code creates a bat
file and executes it.
With Windows 10's default security policy, administrator privileges are required to run correctly.
Clion provides administrator privileges for applications through the following Settings: Edit Configurations
-> selectedRun with Administrator privileges
.
You can see that a copy of the current program is actually created after the run.
Then add this line at the beginning of the main.rs
file.
#![windows_subsystem = "windows"]
Running with Clion is no problem.
But double-click to open it in file Manager. The file will fail to create.Drive C is not going to generate anything.
If you remove the code you just added in the main file, compile it again and open it manually by double-clicking the mouse in the file manager. He can generate success.
#![windows_subsystem = "windows"]
This is the problem I found when writing a program function point that moves its position by itself. Tested in clion everything works fine. But when it runs after publishing, there will be a problem that the file cannot be copied.
In the window system, generally speaking, copying a file can succeed even if the file is occupied. If it is unsuccessful, it is often a permission problem. When I run this bat in cmd without administrator privileges, the copy fails.
C:>copy H:\WorkSpace\clion\cmd_test\target\debug\cmd_test.exe c:\copy_result.exe
access denied.
0 files copied.
PS C:>
So I figured it should be a problem with permissions and #![windows_subsystem = "windows"]
.
In my tests, the creation_flags method and its parameters did not affect the test results of the above.
I don't know if the problem is a design problem of window itself or something to do with rust.
But obviously there is a problem with the permission inheritance of the administrator identity.