GetCurrentDirectory 並沒有真正返回可執行文件的路徑 (GetCurrentDirectory does not really return the path of the executable file)


問題描述

GetCurrentDirectory 並沒有真正返回可執行文件的路徑 (GetCurrentDirectory does not really return the path of the executable file)

我正在使用 c++ 將程序編碼為服務,當我將其作為普通程序進行測試時,函數 GetCurrentDirectory 返回正確的路徑。但是當我嘗試將我的程序安裝為服務時,GetCurrentDirectory 返回 C:\Windows\System32 而不是可執行文件的路徑。

如何我以適用於服務的方式獲取可執行文件的路徑?


參考解法

方法 1:

Working directory for Windows services is always %WINDIR%\System32.

To get directory, where your executable resides, simply call GetModuleFileName with NULL for hModule argument, and manually strip executable name.

方法 2:

Because %WinDir%\System32 is the default working directory for a 32/64 bit Windows service (%WinDir%\SysWOW64 for 32 bit services on 64 bit Windows).

You may set working directory of your service to something else, see also Windows Service: Can I configure the current working directory? or ‑ better ‑ do not rely in your code about working directory. Few options:

  • Read it from registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\<service name>\ImagePath.
  • Use WMI to enumerate services (if you really want to...)
  • Use GetModuleFileName(). It's easy to use but be careful: it has some tricky behavior with WOW64, some virtualization environments and for svcshot hosted services (it's little bit old but you may want to read this article.)
  • Use QueryServiceConfig().

What I'd suggest:

  • Save/load your data in a shared known folder, for example for Common Application Data: SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath).

(by duongtanStarl1ghtAdriano Repetti)

參考文件

  1. GetCurrentDirectory does not really return the path of the executable file (CC BY‑SA 2.5/3.0/4.0)

#service #windows-services #C++






相關問題

服務間數據的參照完整性 (Referential Integrity of Data Between Services)

系統重新啟動時自動啟動星號 (start asterisk autometically when system got restarted)

CanStop 設置為 False 時停止 Windows 服務的方法 (C#) (Way to Stop a Windows Service when CanStop is set to False (C#))

Android: App Widget trong quá trình cập nhật hiển thị hình ảnh lạ (Android: App Widget during update shows strange images)

查找具有特定 startname 的特定服務 (Finding specific services with specific startname)

如何判斷方法是否從 .Net(託管)代碼中的 Windows 服務調用 (How to tell if method is called from Windows Service in .Net (managed) code)

如何使用主屏幕小部件按鈕關閉服務? (How to use a homescreen widget button to shutdown a service?)

如何將版本號放入 rdlc 文件中? (How do you put a version number into an rdlc file?)

android asynTask 到活動問題? (android asynTask to activity problem ?)

GetCurrentDirectory 並沒有真正返回可執行文件的路徑 (GetCurrentDirectory does not really return the path of the executable file)

通知未顯示,因為服務或警報管理器已被終止 (Notification not showing because service or alarm manager is killed off)

當 gunicorn / celery 服務重新啟動時,Django 中有沒有辦法只執行一次 python 代碼? (Is there a way in Django to execute some python code only once when gunicorn / celery services are getting restarted?)







留言討論