【问题标题】:Running a process as background service results in exception将进程作为后台服务运行会导致异常
【发布时间】:2013-11-11 18:28:31
【问题描述】:

以下代码

try {


        String          fileName = "/var/log/syslog";
        File            myFile   = new File(fileName);
        FileInputStream myStream = null;

        System.out.println("canRead()  returns " + myFile.canRead ());
        System.out.println("canWrite() returns " + myFile.canWrite());

        myStream = new FileInputStream(myFile);
        myStream.close();
    }
    catch (FileNotFoundException e)
    {
        System.out.println("FileNotFoundException: " + e);
    }
    catch (IOException e)
    {
        System.out.println("IOException: " + e);
    }

抛出

java.io.FileNotFoundException: /var/log/syslog (Permission denied)

作为后台服务运行时

sudo start server

但作为前台任务运行时成功

exec bin/server.sh

文件存在:

niru@node2:~$ ls -l /var/log/syslog
-rw-r----- 1 syslog adm 616642 Sep  6 15:59 /var/log/syslog

niru 用户 ID 对文件具有读取权限:

 niru@node2:~$ id -a niru
 uid=2001(niru) gid=2001(niru) groups=2001(niru),4(adm),27(sudo)
 niru@node2:~$ head -3 /var/log/syslog
 Aug  1 15:47:57 node kernel: imklog 5.8.6, log source = /proc/kmsg started.
 Aug  1 15:47:57 node rsyslogd: [origin software="rsyslogd" swVersion="5.8.6" x-pid="535" x-info="http://www.rsyslog.com"] start
 Aug  1 15:47:57 node rsyslogd: rsyslogd's groupid changed to 103

谁能告诉我这是什么原因?

【问题讨论】:

    标签: java linux file-permissions permission-denied


    【解决方案1】:

    此权限问题是因为在 Debian 发行版上运行服务的用户的凭据与用户的凭据不同。

    例如,当以“niru”用户名登录时,“id -a”命令会返回以下输出:

    niru@node2:~$ id -a
    uid=2001(niru) gid=2001(niru) groups=2001(niru),4(adm),27(sudo)
    

    在服务进程的上下文中,同样的 'id -a' 命令返回:

    uid=2001(niru) gid=2001(niru) groups=2001(niru)
    

    因此,在服务上下文中,niru 用户 ID 没有读取 /var/log/syslog 文件的权限。

    This bug in Upstart is documented here: https://bugs.launchpad.net/upstart/+bug/812870
    

    将 setgid 参数添加到服务启动文件解决了该问题。

    【讨论】:

      【解决方案2】:

      通过运行sudo start server,进程不再以用户niru 运行,因此不再有权访问系统日志文件。

      【讨论】:

      • 但是当我对该过程执行 ps 时,我将用户视为 niru。那会是什么原因呢?很好,用户 niru 具有 sudo 权限。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 2020-03-21
      • 2019-01-03
      • 2011-05-13
      相关资源
      最近更新 更多