2

我在 Vista SP1 上有一个 Windows 服务应用程序,我发现用户正在重命名其可执行文件(在它运行时)然后重新启动,从而导致它在下次启动时无法启动,因为服务管理器无法再找到 exe文件,因为它已被重命名。

我似乎记得在旧版本的 Windows 中你不能这样做,因为操作系统在文件上设置了锁。即使使用 Vista SP1,我仍然无法在现有文件运行时复制它 - Windows 报告该文件正在使用中 - 是有道理的。那么为什么我应该被允许重命名呢?如果 Windows 需要从 exe 中调入新的代码页,但文件自启动后已被重命名,会发生什么情况?我在重命名 exe 文件等时运行了 Process Monitor,但 Process Mon 没有报告任何奇怪的事情,只是像任何其他文件一样记录了更改文件名。

有谁知道幕后发生了什么?Windows 允许更改正在运行的进程的文件名(或其依赖的 DLL)似乎违反直觉。我在这里想念什么?

4

6 回答 6

3

你的概念是错误的......文件名不是文件io宇宙的中心......打开文件的句柄是。重命名文件时,文件不会移动到磁盘的不同部分,它仍然在同一个位置,并且打开文件的内部数据结构的磁盘部分仍然指向同一个位置。底线是你的观察是正确的。您可以重命名正在运行的程序而不会引起问题。重命名后,您可以创建一个与正在运行的程序同名的新文件。如果您想在软件运行时更新软件,这实际上是有用的行为。

于 2009-04-28T20:28:44.333 回答
2

只要文件仍然存在,Windows 仍然可以从中读取 - 重要的是底层文件,而不是它的名称。

我可以愉快地重命名我的 XP 机器上正在运行的可执行文件。

于 2009-04-28T20:24:10.960 回答
0

The OS keeps an open handle to the .exe file,. Renaming the file simply changes some filesystem metadata about the file, without invalidating open handles. So when the OS goes to page in more code, it just uses the file handle it already has open.

Replacing the file (writing over its contents) is another matter entirely, and I'm guessing the OS opens with the FILE_SHARE_WRITE flag unset, so no other processes can write to the .exe file.

于 2009-04-28T20:36:09.543 回答
0

Might be a stupid question but, why do users have access to rename the file if they are not suppose to rename the file? But yeah, it's allowed because, as the good answers point out, the open handle to the file isn't lost until the application exits. And there are some uses for it as well, even though I'm not convinced updating an application by renaming its file is a good practice.

于 2009-04-28T20:46:54.960 回答
0

您可能会考虑让您的服务侦听对安装服务的目录的更改。如果它检测到重命名,那么它可以将自身重命名回它应该是的。

于 2009-04-28T20:56:57.310 回答
0

这里文件的概念有两个方面:

  1. 磁盘上的数据- 那是实际的文件。

  2. 您可以提供该数据的文件名(可以是多个或没有) - 称为目录条目。

您正在重命名的是目录条目,它仍然引用相同的数据。Windows 并不关心您这样做,因为它仍然可以在需要时访问数据。正在运行的进程映射到数据,而不是名称。

于 2015-02-16T14:02:26.817 回答