I have a question regarding the getlogin() function (). I tried to get the login name of my account from the c program using this function. But the function returns a NULL. Using perror shows that the error is "No such file or directory".
I don't get what is the problem. Is there a way to get user login name in a program.
Here is a sample code:
#include <stdio.h>
#include <unistd.h>
int main()
{
char *name;
name = getlogin();
perror("getlogin() error");
//printf("This is the login info: %s\n", name);
return 0;
}
And this is the output: getlogin() error: No such file or directory
Please let me know how to get this right.
Thanks.
getlogin
is an unsafe and deprecated way of determining the logged-in user. It's probably trying to open a record of logged-in users, perhaps utmp
or something. The correct way to determine the user you're running as (which might not be the same as the logged-in user, but is almost always better to use anyway) is getpwuid(getuid())
.
Here is a good link I found explaining that it may not work: getlogin
Here is a quote from it:
Unfortunately, it is often rather easy to fool getlogin(). Sometimes it does not work at all, because some program messed up the utmp file
It works fine for me if I comment perror
call.
From man
:
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.'
So you should do:
#include <stdio.h>
#include <unistd.h>
int main()
{
char *name;
name = getlogin();
if (!name)
perror("getlogin() error");
else
printf("This is the login info: %s\n", name);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With