go在linux不同启动方式导致os.getwd()获取路径错误
当使用go打包的程序在linux上以不同方式启动时,调用os.getwd()获取当前工作路径可能出现不一致的问题。
问题描述
原因分析
systemd默认工作目录为“/”,而nohup启动方式会沿用当前工作目录。因此,在systemctl启动下,os.getwd()获取的是系统的默认工作目录,而不是程序所在目录。
解决办法
在systemd服务配置中,添加workingdirectory选项指定程序的工作目录:
[Unit] Description=My Go Service [Service] WorkingDirectory=/path/to/my/program ExecStart=/path/to/my/program ...
这样,在systemctl启动程序时,工作目录将被正确指定到程序所在目录,从而解决路径获取问题。