Search code examples
cbashuser-inputstdineol

Simulate input to STDIN with EOL


I am testing a method to simulate a specific input to an application. This is the application:

#include <stdio.h>

int main()
{
        int num1;
        char buffer[6] = {0};

        scanf("%d", &num1);
        read(0, buffer, 6);

        printf("num1 = %d\n", num1);

        for(num1=0; num1 < 6; num1++)
        {
                printf("%02X\n", buffer[num1]);
        }

        return 0;
}

I am trying to simulate the input using the following bash command:

echo -ne "1337\\x0A\\x31\\x02\\x03\\x04\\x05\\x06" | ./test

The output I get is the following:

num1 = 1337
00
00
00
00
00
00

As you can see, the buffer was not filled with values passed to the STDIN.

EDIT: The function below is only used to illustrate an idea of input automation in mixed i/o functions, I got this function by reverse engineering a binary file, is it possible to automate the input ?

I appreciate your help.

Thanks,


Solution

  • What's happening here?

    • echo is making a write with exactly as many characters you put in the command line (as you use -n flag it doesn't output a final \n char).
    • you are using scanf() on a pipe, so it makes a full buffer read first, and then scans the buffer for an integer. It does a n = read(0, buffer, BUFSIZ); returning 11 as the number of characters read to scanf and then scanf scans the buffer, returning 1337 as the number read and leaving all the characters past it into the buffer.
    • then you do a read(0, buffer, 6); that returns 0 and the buffer is not initialized with data.
    • then you print the previous, uninitialized buffer contents to stdout.

    fifos (or pipes) behave quite different than terminals on input. The terminal driver just makes a read to complete when you push the enter key, making read to get the actual number of characters read by one input line. When you do this with a fifo, the reader process is blocked until enough characters (the actual number requested by read) is fed to the process and then that number (actually the requested number of characters) is returned by read.

    If you had the precaution of checking the read(2) return value, you should get the actual number of read chars (that should be 0 as the scanf(3) has eaten the complete buffer as it is smaller than BUFSIZ constant, in the first read)