我想在我的程序中捕获通过 GUI 登录的用户名。我的程序作为守护进程从 root 登录运行。如果非 root 用户通过 GUI 登录,我的程序应该会收到通知。
我正在粘贴我当前的程序,该程序调用一个 perl 脚本,利用系统调用来检查当前登录的用户是谁。我也粘贴我的 perl 脚本以供参考。
#include <X11/Xlib.h>
#include <X11/Xos.h>
#include <X11/Xfuncs.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
int main()
{
char *user;
char buf[1024];
int fd, ret;
fd = open("/tmp/log", O_TRUNC|O_RDWR|O_CREAT);
if (!fd) {
printf("Error opening file\n");
exit(1);
}
chmod("/tmp/log", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP
| S_IROTH | S_IWOTH | S_IXOTH);
daemon(0, 0);
while (1) {
system("perl /home/curr-usr.pl");
sleep(5);
}
return 0;
}
Perl 脚本用于获取当前用户登录。
#!/usr/bin/perl
my $result;
$result = `whoami`;
open FH, "+>>", "/tmp/log" or die $!;
print FH "$result ";
close (FH);
在上面的 c 程序中,我每 5 秒在 while 循环中调用一次 perl 脚本。 Perl 脚本使用命令“whoami”来获取当前用户登录并将其转储到 /tmp/log 文件中。
我想要实现的是,如果 user1 登录 perl 脚本应该给我当前用户为 user1。相反,当我使用 root 用户运行 C 程序和 perl 脚本时,perl 脚本将 root 作为当前用户,而不管我通过 GUI 登录的用户是什么。
谁能告诉我一种机制,让 C 程序可以了解通过 GUI 登录的当前用户?
任何帮助是极大的赞赏。
您可以使用主显示屏检测用户,如下所示:
#!/bin/bash
#Detect the name of the display in use
display=":$(ls /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)"
#Detect the user using such display
user=$(who | grep '('$display')' | awk '{print $1}')
#Detect the id of the user
uid=$(id -u $user)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)