切换至pvmonitor用户后C++守护进程打开配置文件提示Permission denied问题求助
切换至pvmonitor用户后C++守护进程打开配置文件提示Permission denied问题求助
大家好,我遇到了一个权限相关的棘手问题,希望能得到各位的帮忙:
我正在开发一个用于家庭自动化的C++守护进程,最终要部署在运行Raspberry Pi OS的树莓派上。程序需要以root权限启动——因为启动后得读取一个只有root拥有读取权限的SSL证书,等证书读取完成后就不再需要root权限了,所以我用setuid(iUid)切换到了pvmonitor用户(UID为1004),并且通过ps命令确认进程确实已经以这个用户身份运行。
配置文件位于/etc/SmartHome/coverd.conf,属主是pvmonitor,相关权限信息如下:
ls -la /etc/SmartHome/ total 24 drwxrwx---+ 2 pvmonitor www-data 4096 Jul 5 21:47 . drwxr-xr-x+ 107 root root 4096 Jul 15 09:44 .. -rwxrwx---+ 1 pvmonitor www-data 705 Jul 5 21:47 coverd.conf
另外,树莓派是网络启动的,文件系统从NAS挂载,并且设置了ACL,pvmonitor用户拥有该文件的访问权限:
getfacl /etc/SmartHome/coverd.conf getfacl: Removing leading '/' from absolute path names # file: etc/SmartHome/coverd.conf # owner: pvmonitor # group: www-data [...] user:pvmonitor:rwx [...]
手动用sudo -u pvmonitor less /etc/SmartHome/coverd.conf可以正常读取配置文件,但我的守护进程切换用户后调用fopen打开该文件时,却返回“Permission denied”错误。
以下是最小复现代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <unistd.h> const char *ptConfigFile = "/etc/SmartHome/coverd.conf"; void printConfig( void ) { std::cout << "Try to open file " << ptConfigFile << std::endl; FILE *ptfTest; ptfTest = fopen( ptConfigFile, "r" ); if (ptfTest != nullptr) { char sLine[1024]; while (!feof(ptfTest)) { fgets(sLine,1023,ptfTest); std::cout << sLine; } fclose( ptfTest ); } else perror( "Failed to open file" ); } int main(int argc, char **argv ) { int iUid = 1004; std::cout << "User id is now " << getuid() << std::endl; printConfig(); std::cout << "Switch to user id " << iUid << std::endl; if (iUid == 0 || setuid(iUid)== 0) { std::cout << "User id is now " << getuid() << std::endl; printConfig(); return 0; } std::cerr << "Could not switch user id." << std::endl; return -1; }
运行程序后的输出:
sudo ./test User id is now 0 Try to open file /etc/SmartHome/coverd.conf CERTFILE=[...] [...] Switch to user id 1004 User id is now 1004 Try to open file /etc/SmartHome/coverd.conf Failed to open file: Permission denied
请问我哪里做错了?
内容来源于stack exchange
相关产品推荐
相关产品推荐

