在低级C图形代码中管理Linux帧缓冲(fb0)权限

3

我正在尝试使用C语言在Linux上学习低级图形编程。我对Linux和C都比较陌生。我正在尝试找出在代码中管理/dev/fb0权限的最负责任方式。

我的代码:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

int main(){

    int fb_fd = 0;
    // Open the file for reading and writing
    fb_fd = open("/dev/fb0", O_RDWR);
    if (fb_fd == -1) {
    perror("Error: cannot open framebuffer device");
    exit(1);
    }
    printf("The framebuffer device was opened successfully.\n");

    struct fb_fix_screeninfo finfo;
    struct fb_var_screeninfo vinfo; 
    //Get variable screen information
    ioctl(fb_fd, FBIOGET_VSCREENINFO, &vinfo);

    //Get fixed screen information
    ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo);

    printf("vinfo.bits_per-pixel: %d\n",vinfo.bits_per_pixel);
    close(fb_fd);
    return(0);
}

我的问题是:程序只能使用sudo ./my_program运行,否则会无法打开帧缓冲区(权限被拒绝)。我不确定在编写旨在绘制到帧缓冲区的软件时如何通常管理/dev/fb0的权限。如何“授予权限”给我的程序,使其可以由普通用户运行而无需特殊权限?

编辑:按要求提供一些控制台输出:

设置模式和权限

~/learning_c/game_0$ ls -l /dev/fb0
crw-rw---- 1 root video 29, 0 Oct 28 08:01 /dev/fb0
~/learning_c/game_0$ ls -l ./bin/game
-rwxrwxr-x 1 logan logan 15160 Oct 29 21:12 ./bin/game
~/learning_c/game_0$ chgrp video ./bin/game
chgrp: changing group of './bin/game': Operation not permitted
~/learning_c/game_0$ sudo chgrp video ./bin/game
[sudo] password for logan:
~/learning_c/game_0$ ls -l ./bin/game
-rwxrwxr-x 1 logan video 15160 Oct 29 21:12 ./bin/game
~/learning_c/game_0$ sudo chmod -v  g+s ./bin/game
mode of './bin/game' changed from 0775 (rwxrwxr-x) to 2775 (rwxrwsr-x)
~/learning_c/game_0$ ls -l ./bin/game
-rwxrwsr-x 1 logan video 15160 Oct 29 21:12 ./bin/game

尝试运行./bin/game。
~/learning_c/game_0$ ./bin/game
Error: cannot open framebuffer device: Permission denied
logan@logan-Aspire-5560:~/learning_c/game_0$ sudo ./bin/game
[sudo] password for logan:
The framebuffer device was opened successfully
1个回答

1

/dev/fb0 通常对于组 video 是可读写的:

$ ls -la /dev/fb0

crw-rw---- 1 root video 29, 0 Oct 11 12:40 /dev/fb0

你可以将你的程序归属于组 video:

chgrp video my_program

并将 sgid 位设置在其上:
chmod g+s my_program

这将设置您的进程的所谓有效 gid (egid),而真实 gid 是从父进程继承的。现在,即使不以 root 用户身份运行,您的程序也应该有打开 framebuffer 设备的权限。
出于安全考虑,您可以(应该?)通过将有效 gid 设置为真实 gid,在打开设备文件后放弃这些额外的特权:
fb_fd = open("/dev/fb0", O_RDWR);
setegid(getgid());

这样做应该可以按照您的意愿工作。

感谢您的帮助。假设您对chgrpchmod的建议是通过命令行运行,但我似乎没有得到预期的结果。我以详细模式运行它们以验证它们是否更改了组和文件模式位,但程序仍然被拒绝访问而需要使用sudo。命令行脚本是程序员获取访问帧缓冲区权限的典型方式吗? - Logan Bender
通过 ls -l 检视文件模式,我看到 -rwxr-xr-x,这表示组拥有 xr- 权限(没有 w 权限)。该代码正在以 O_RDWR 模式打开文件。视频组也需要写入权限吗? - Logan Bender
@LoganBender 这个模式是在哪个文件中?/dev/fb0?请展示 ls -l /dev/fb0ls -l my_program 的完整输出。 - Ctx
为OP添加了注释 - Logan Bender

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接