Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

File descriptor automatically updated to end of file

Consider this example (for brevity’s sake, I’ve omitted headers and error checking):

int main() {
    int fd;

    fd = open("dump", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);

    if ( fork() > 0 ) {
        sleep(1);
        printf("Current offset: %li\n", (long)lseek(fd, 0, SEEK_CUR);
        write(fd, "zz", 2);
    }
    else {
        write(fd, "hello\n", 6);
    }

    close(fd);
    return 0;
}

This program (run on Linux) prints

Current offset: 6

to the terminal and

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hello
zz%

to dump (% signifying the lack of a newline character).

Why doesn’t dump contain

zzllo

?

My thinking is, after fork, there are two file descriptors to the same process but each with its own offset. Why does writing to one descriptor affect the other?

>Solution :

Processes have their own file descriptors but those act as reference-counted pointers to shared file descriptions. The sharing of file descriptions is what allows, e.g., shell scripts to do stuff such as

(
 /usr/bin/echo hello
 /usr/bin/echo world 
) > some_file

and have some_file contain both hello and world.

It also allows applications that modify terminal settings (stty), a utility such as flock (that places a lock into the shared filedescription), and possibly other stuff.

(BTW, you should use lseek with a filedescriptor. fseek accepts a FILE pointer).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading