通过守护程序获取当前用户登录 Linux

Get Current user login to Linux via Daemon

我正在记录一个以 1 分钟为间隔登录到 linux 系统的用户。日志记录将使用 root 拥有的 init.d 脚本完成,它会在启动时自动启动。

我尝试通过简单的 init.d 脚本使用 getlogin() 和 getlogin_r()。但是,如果我通过控制台 运行 init.d 脚本但当我通过 chkconfig --add [initscript] 注册 init.d 脚本并重新启动系统时,它会工作 运行s 通过 ps -ef 检查但是当我检查日志文件时,用户名是空的。

我错过了什么吗?他们是获取登录用户的替代方法吗?

getlogin() returns a pointer to a string containing the name of the user logged in on the controlling terminal of the process, or a null pointer if this information cannot be determined.

通过 init 的脚本 运行 没有控制终端。然而,如果您 运行 通过控制台编写脚本,则控制台就是控制(虚拟)终端。

getlogin()没有做你想做的事。我假设您应该查看 userswho 命令。

@ypnos, 我没有费心检查你从 link github.com/coreutils/coreutils/blob/master/src/who.c.

提供的 who.c

我采用了与下面的代码片段不同的方法。

#include <stdio.h>
#include <utmpx.h>
#include <time.h>


int main (void)
{
    struct utmpx *UtmpxPtr = NULL;
    struct tm *TimePtr = NULL;
    time_t TimeInSec;
    char TimeBuff[32];

    printf("...Start \"who logged-in\"...\n");

    setutxent();
    while ((UtmpxPtr = getutxent()) != NULL)
    {
        if (UtmpxPtr->ut_type != USER_PROCESS)
        {
            continue;
        }

        TimeInSec = UtmpxPtr->ut_tv.tv_sec;
        TimePtr = localtime(&TimeInSec);
        strftime(TimeBuff, sizeof(TimeBuff), "%Y-%m-%d|%H:%M", TimePtr);

        printf("%s|%s|%s\n", UtmpxPtr->ut_user, TimeBuff, UtmpxPtr->ut_host);
        fflush(stdout);
    }

    endutxent();
    return 0;
}