1、问题描述
开发程序过程中,使用qApp->applicationDirPath()返回程序所在目录,一直没问题。但是在设置自启动后,qApp->applicationDirPath()返回的目录不是程序所在目录。
2、原因分析
查看qApp->applicationDirPath()官方手册,发现针对Linux系统,有如下警示说明:
Warning: On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.
大意是:在Linux系统中,该函数尝试获取 /proc 中记录的路径;如果获取失败,在从argv[0]中获取绝对路径。这个函数假设程序没有更改当前目录。
对比查看 /proc/[PID]/cwd 链接的路径:开发时,启动程序在进入程序所在目录后启动,此时 /proc/[PID]/cwd 链接到程序所在目录;在设置为自启动后,启动脚本直接在root根目录下使用程序的绝对路径启动,此时 /proc/[PID]/cwd 链接的是root根目录。
3、解决方法
在设置启动脚本时,先 cd 到程序所在目录,然后再执行程序。
应该还有其它方法,比如获取程序绝对路径qApp->applicationFilePath(),然后截取出程序路径(这个方法没有测试)。
如果我的能力只能让我穷困潦倒,那穷困潦倒就是我的价值。