cbash

C program called in a bash loop incrementally reading from a single file never exiting


int main() {
    char buf[2];
    read((0, buf, 2);
    lseek(0, 1, SEEK_CUR);
    write(1, buf, 2);
}

The rwl program, whose source code is shown on the top, is run with the following command on a 2-line fileA text file with "01234" data on each line. Determine the data that this command will display and the changes that must be made to the rwl source code in order for the command to be terminated.

$> while rwl; do :; done < fileA

This is an old exam question. Can someone help me solve it?

I tried to put a while(read(0, buf, 2) > 0) and put other 2 inside of loop but it didnt work.


Solution

  • This is a C problem more than a bash problem: Your program isn't checking for errors, so it never detects that it was unable to read additional content from the file successfully, and correspondingly never tells bash that it failed -- so the loop never exits.

    #include <unistd.h>
    #include <stdlib.h>
    
    int main() {
        char buf[2];
        int retval;
    
        retval = read(0, buf, 2);
        if (retval != 2) { exit(1); }
    
        retval = lseek(0, 1, SEEK_CUR);
        if (retval < 0) { exit(1); }
    
        retval = write(1, buf, 2);
        if (retval != 2) { exit(1); }
    }