N
N
nak-alexey2021-07-31 22:00:59
linux
nak-alexey, 2021-07-31 22:00:59

How to find out which user is logged into the linux system in si?

Hello. How to find out which user is logged into the linux system in si? That is, which one is active now? Is there any library for these things?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Sergey Karbivnichy, 2021-07-31
@hottabxp

Option 1:

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
    char *cmd = "whoami";
    char buf[BUFSIZ];
    FILE *ptr;
 
    if ((ptr = popen(cmd, "r")) != NULL)
        while (fgets(buf, BUFSIZ, ptr) != NULL)
            (void) printf("%s", buf);
            (void) pclose(ptr);
    return 0;
}

Option 2:
#include <stdlib.h>
 
int main(int argc,char **argv)
{
    system("whoami");
    return 0;
}

Both options will return the name of the current user.
6105a1ae3529f141836768.png

M
mikhanoid, 2021-07-31
@mikhanoid

You can start with man utmp.

M
Melkij, 2021-07-31
@melkij

If it works for postgresql, then it probably works for you too: https://github.com/postgres/postgres/blob/REL_13_S...
(geteuid + getpwuid under linux)

S
shurshur, 2021-08-01
@shurshur

man getuid
man getpwuid
There are standard functions for such tasks. They are much more correct to use than parsing utmp (which the user may not get into, especially if it is a non-interactive login or su / sudo) and /etc/passwd (since users can be stored not only in passwd, but also in winbind/ldap/nis/ etc).

I
Igor Ivanov, 2021-08-05
@PlugIN

Would this not work: `system("who -a")`? Need 'stdlib.h'. Source: https://www.techonthenet.com/c_language/standard_l...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question