Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling of EOF in lsh_read_line() #25

Open
robsim0116 opened this issue Aug 10, 2024 · 1 comment · May be fixed by #26
Open

Handling of EOF in lsh_read_line() #25

robsim0116 opened this issue Aug 10, 2024 · 1 comment · May be fixed by #26

Comments

@robsim0116
Copy link

Hi :) I just wanted to contribute to your excellent tutorial by (I think) improving the error handling in lsh_read_line(). Unless I'm mistaken, I don't think it currently handles the case when EOF actually indicates a read error and not a "successful" EOF/an EOF proper. My own code for the while loop looks more or less like this at the moment (you can see I'm (a) checking for the meaning of the returned EOF and (b) ensuring the buffer is freed before exiting):

// rest of code

while (1) {
        c = getc(stdin);
        
        if (c == '\n') {
            rl_buf[pos] = '\0';
            return rl_buf;
        } else if (c == EOF && ferror(stdin)) {
            fprintf(stderr, "ERROR: read error (%d)\n", errno);
            free(rl_buf);
            exit(EXIT_FAILURE);
        } else if (c == EOF && feof(stdin)){
            free(rl_buf);
            exit(EXIT_SUCCESS);
        }

        rl_buf[pos] = c;
        pos++;
        
        // rest of code
}

What do you think? Have I made a mistake in my reasoning?

@brenns10
Copy link
Owner

brenns10 commented Aug 24, 2024

You're definitely correct! If you'd like to submit a pull request with that change, I'd be happy to merge it. One slight change I would suggest is rather than the fprintf() call you have, you can use the perror(3) function:

perror("getchar");

This will automatically lookup what the error was (using the errno variable and then strerror(3)), and it will print that message to stderr, prefixed by whatever you put in as the first string argument. So, for example, you might get something like this printed to stderr:

getchar: Bad file descriptor

robsim0116 added a commit to robsim0116/lsh that referenced this issue Aug 25, 2024
@robsim0116 robsim0116 linked a pull request Aug 25, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants