Program to display all logged in users via C program on Ubuntu?

后端 未结 1 474
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 07:40

I have one program called allloggedin.c, whose purpose is to display all logged in users.

Whenever I try to run it on terminal (using gcc), it gives me erro

相关标签:
1条回答
  • 2021-01-29 08:06

    The Segmentation Fault you are getting is because of the line:

    printf("%c",a[i]);
    

    Since you didn't initialize the pointer a, it can point to any address, which may cause a Segmentation Fault when you dereference it.

    I'm not sure what you are trying to print in the for loop so I removed it entirely from the code.

    This is a cleaned version of the code:

    #include<stdio.h>
    #include<sys/utsname.h>
    #include<utmp.h>
    
    int main(void)
    {
      struct utmp *n;
      setutent();
      n=getutent();
    
      while(n) {
        if(n->ut_type==USER_PROCESS) {
          printf("%9s%12s (%s)\n", n->ut_user, n->ut_line, n->ut_host);
        }
        n=getutent();
      }
      return 0;
    }
    

    I replaced the number 7 by the proper macro USER_PROCESS. Also, you can place all the prints in a single printf call.

    So what the program basically does is to get the utmp struct for each user and print it in a fancy way.

    For more information about the functions used and the utmp struct you can take a look at the utmp.h reference.

    0 讨论(0)
提交回复
热议问题