Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getlogin() c function returns NULL and error "No such file or directory"

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.

like image 861
yaami Avatar asked Jan 24 '11 17:01

yaami


3 Answers

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()).

like image 72
R.. GitHub STOP HELPING ICE Avatar answered Oct 21 '22 02:10

R.. GitHub STOP HELPING ICE


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

like image 42
Nick Banks Avatar answered Oct 21 '22 02:10

Nick Banks


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;
}
like image 43
Elalfer Avatar answered Oct 21 '22 02:10

Elalfer