如何检测Linux中通过GUI登录的用户 [英] How to detect a user logged in through GUI in Linux

查看:93
本文介绍了如何检测Linux中通过GUI登录的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获通过GUI在程序中登录的用户名.我的程序从root登录作为守护程序运行.如果非root用户通过GUI登录,则应通知我的程序. 我正在粘贴当前程序,该程序使用系统调用来调用perl脚本,以检查谁是当前登录用户.我也正在粘贴我的perl脚本,以供参考.

I would like to capture the user name logged in through GUI in my program. My program is running as a daemon from root login. If a non root user logs in through GUI my program should be notified. I am pasting my current program which calls a perl script making use of system call to check who is the current user logged in. I am pasting my perl script too for reference.

#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脚本.

The perl script which is used to get the current user logged in.

#!/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文件中.

In the c program above I am calling the perl script in a while loop every 5 seconds. The perl script makes use of the command "whoami" to get the current user logged in & dumps it into the /tmp/log file.

我要实现的是,如果user1登录到perl脚本中,则应该给我当前用户为user1.取而代之的是,无论我在运行C程序&时通过GUI登录的用户如何,perl脚本都将root作为当前用户.具有root用户的perl脚本.

What I want to achieve is if user1 logs in the perl script should give me the current user to be user1. Instead the perl script gives me root as the current user irrespective of the user I am logged in through GUI as I am running the C program & perl script with root user.

任何人都可以通过C程序了解通过GUI登录的当前用户的机制为我提供建议吗? 任何帮助,我们将不胜感激.

Could anyone please advise me with a mechanism by which the C program could get to know the current user logged in through GUI ? Any help is greatly appreciated.

推荐答案

您可以使用如下所示的主显示来检测用户:

You can detect the user using the main display like this:

#!/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)

这篇关于如何检测Linux中通过GUI登录的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆