[英]Linux daemon: alternative to chdir(“/”)?
I have a program (Crafty chess) that works just fine when started from the console. 我有一个程序(Crafty Chess),从控制台启动后就可以正常工作。 For my application I have daemonized it. 对于我的应用程序,我已将其守护进程。 When daemonizing a process, one is supposed to change the working directory to "/" via chdir("/")
. 守护进程时,应该通过chdir("/")
将工作目录更改为“ /”。
When I follow that advice, the program exits in some use cases because it doesn't have the proper permissions in "/". 当我遵循该建议时,该程序在某些用例中退出,因为它在“ /”中没有适当的权限。 When I don't chdir
, the program works, but just leaving out chdir
is a crutch. 当我不使用chdir
,该程序可以运行,但是仅chdir
就是一个拐杖。
Is there a sound alternative to omitting chdir("/")
? 有没有替代chdir("/")
的声音替代方法?
It probably should not write to the current directory. 它可能不应该写入当前目录。 It'd be better to write to some specific directory instead. 最好改写一些特定的目录。 Instead of cd'ing to /tmp
and writing files to the current directory, write files to /tmp/whatever
— ie always use absolute paths. 与其将CD刻录到/tmp
并将文件写入当前目录,不如将文件写入/tmp/whatever
文件-即始终使用绝对路径。
And on a related note, don't hardcode /tmp
if you can avoid it. 另外,如果可以避免,请不要对/tmp
进行硬编码。 Make it a configuration option, or use the $TMPDIR
environment variable, or best of all, use mktemp()
. 使其成为配置选项,或者使用$TMPDIR
环境变量,或者最重要的是,使用mktemp()
。
You can call the daemon(3) function (with a non-zero first nochdir
argument) so that it daemonize a process without doing the chdir("/")
) 您可以调用daemon(3)函数(带有一个非零的第一个nochdir
参数),以便它不用执行chdir("/")
就可以守护进程。
But as John Kugelman suggests, you should not write (nor read) any relative path in a daemonized program (or you should do an explicit chdir
to a directory that you can read and write and search). 但是,正如约翰·库格曼(John Kugelman)所建议的那样,您不应在守护程序中写入(也不读取)任何相对路径(或应对可以读取,写入和搜索的目录执行显式chdir
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.