Gam
Gam

Reputation: 694

Strange behavior with read()

I discovered the function read(), but I don't understand everything. Here is my code:

#include <unistd.h>
#include <stdio.h>

int     main(void)
{
    char array[10];
    int  ret;

    printf("read : ");
    fflush(stdout);

    array[sizeof(array) - 1] = '\0';
    ret = read(STDIN_FILENO, array, sizeof(array) - 1);

    printf("array = %s\n", array);
    printf("characters read = %d\n", ret);

    //getchar();

    return (0);                 
}

Here is an example of the running program :

$> ./a.out
read : hi guys how are you
array = hi guys h
characters read = 9
$> ow are you
zsh: command not found: ow
$>

Why is it launching a shell command after the end of the program? I noticed that if I uncomment the getchar() line, this strange behavior disappears. I'd like to understand what is going on, if someone has an idea :)

Upvotes: 0

Views: 78

Answers (2)

Chris Turner
Chris Turner

Reputation: 8142

Your call to read is reading in the first 9 characters of what you've type. Anything else will be left in the input buffer so that when you program exits, your shell will read it instead.

You should check the return value of read so you know how much has been read as it's not guaranteed that it'll be the amount you ask for and also the value returned is used to indicate an error.

The string read in won't be null-terminated either, so you also should use the return value (if positive) to put the NUL character in so that your string is valid.

If you want to read in the whole line, you'll need to put in a loop and identify when there is an end of line character (most likely '\n').

Upvotes: 3

Barmar
Barmar

Reputation: 782683

You typed about 20 characters, but you only read 9 characters with read(). Everything after that was left in the terminal driver's input buffer. So when the shell called read() after the program exited, it got the rest of the line, and tried to execute it as a command.

To prevent this, you should keep reading until you get to the end of the line.

Upvotes: 2

Related Questions