getpwnam() завершает работу программы при вводе неверного пользователя

В getuserinfo() если строка struct passwd *theUser = getpwnam(имя пользователя); выполняется с именем пользователя, которого не существует, программа просто закрывается с ошибкой -1. Он никогда не попадает в часть обработки ошибок функции. Это не возвращается к основному, и я не уверен почему.

Он должен вернуть NULL и распечатать сообщение об ошибке и позволить остальной части программы попытаться запустить.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>


//awk 'BEGIN { FS=":"; print "User\t\tUID\n--------------------"; } { print $1,"\t\t",$3;} END { print "--------------------\nAll Users and UIDs Printed!" }' /etc/passwd
#define SHELLSCRIPT "\
#/bin/bash \n\
awk 'BEGIN { FS=\":\"; print \"User\t\tUID\n--------------------\"; } { print $1,\"\t\t\",$3;} END { print \"--------------------\nAll Users and UIDs Printed!\" }' /etc/passwd \n\
    "



struct passwd *getuserinfo(char *username)
{
    //Set errno to 0 so we can use it
    errno = 0;

    //create a variable to store the user info in
    struct passwd *theUser = getpwnam(username);

    //error check getpwnam()
    if(theUser == NULL)
    {
        printf("getpwnam() ERROR, errno = %d", errno);
        return NULL;
    }

    return theUser;
}

struct group *getgroupinfo(long int groupid)
{
    //Set errno to 0 so we can use it
    errno = 0;

    //create a variable to store the group info in
    struct group *theGroup = getgrgid(groupid);

    //error check getgrgid()
    if(theGroup == NULL)
    {
        printf("getgrgid() ERROR, errno = %d", errno);
        return NULL;
    }

    return theGroup;
}

void displayusers()
{
    system(SHELLSCRIPT);
}

/*
 *
 *  4. A main function which will
 * Call getuserinfo passing a hard-coded username, and using the return object, display the user id. (10 points)
 * Call getgroupinfo passing the return object from getuserinfo, and using the return object, display the user’s group name. (10 points)
 * Call displayusers. (10 points)
 *
 * My main function does those things but I don't pass objects since the function prototypes you gave us
 * don't accept that input, they want ints and strings
 */

int main(int argc, char **argv)
{
    //Take in the username we want to look up
    char username[50];
    printf("Enter username: ");
    scanf("%s", username);


    //look up the user and get their info
    struct passwd *theUser = getuserinfo(username);
    //use the user's gid and look up its info
    struct group *theGroup = getgroupinfo(theUser->pw_gid);

    printf("User: %s\nUser ID: %d\nGroup Name: %s\n\n\n", theUser->pw_name, theUser->pw_uid, theGroup->gr_name);

    displayusers();


    return 0;
}

1 ответ

Проверка ошибок должна выглядеть так:

struct passwd *getuserinfo(char *username)
{


//define errno so we can use it
errno = 0;
//create a variable to store the user info in
struct passwd *theUser = getpwnam(username);

//error check getpwnam()
if(errno != 0)
{
    perror("ERROR: getpwnam() FAIL");
}
//check if we got user data/if the user existed
else if(theUser == NULL)
{
    fprintf(stderr, "ERROR: User does not exist!\n");
    return NULL;
}

    return theUser;
}

Необходимо использовать fprintf с использованием stderr, чтобы сообщение об ошибке всегда отображалось. Он терялся в буфере printf, и Кейтмо предложил использовать fflush(NULL).

errno используется для проверки успешности вызова. Затем мы проверяем theUser!= NULL, потому что вызов успешен, даже если отсутствует пользователь. Если это NULL, мы печатаем сообщение об ошибке пользователю, чтобы он знал.

Мы также проверяем ошибки, прежде чем мы вызовем getgroupinfo в основной функции сейчас согласно t0mm13b

//look up the user and get their info
    struct passwd *theUser = getuserinfo(username);
    //use the user's gid and look up its info
    struct group *theGroup;
    if(theUser != NULL)
    {
        //get the user's group id
        theGroup = getgroupinfo(theUser->pw_gid);
        //print the user and group info
        printf("User: %s\nUser ID: %d\nGroup Name: %s\n\n\n", theUser->pw_name, theUser->pw_uid, theGroup->gr_name);
    }
    else
    {
        fprintf(stderr, "ERROR: No group info, missing user!\n");
    }


    displayusers();
Другие вопросы по тегам