O'Reilly logo

The Linux Programming Interface by Michael Kerrisk

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix F. Solutions to Selected Exercises

  1. A solution is provided in the file fileio/atomic_append.c in the source code distribution for this book. Here is an example of the results that we see when we run this program as suggested:

    $ ls -l f1 f2
    -rw-------    1 mtk      users     2000000 Jan  9 11:14 f1
    -rw-------    1 mtk      users     1999962 Jan  9 11:14 f2

    Because the combination of lseek() plus write() is not atomic, one instance of the program sometimes overwrote bytes written by the other instance. As a result, the file f2 contains less than 2 million bytes.

  2. A call to dup() can be rewritten as:

    fd = fcntl(oldfd, F_DUPFD, 0);

    A call to dup2() can be rewritten as:

    if (oldfd == newfd) { /* oldfd == newfd is a special case */ if (fcntl(oldfd, F_GETFL) == -1) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required