News for hackers. Stuff that matters.
Re:Things UNIX can do atomically by prodigal_erik on Wednesday January 06, 2010 @01:55PM (#1035410)

  pipe(&pipefd);
  assert(len <= PIPE_BUF);
  write(pipefd[1], buf, len);
Also, if a file is opened O_APPEND, the seek before every write is atomic, but since writes in general aren't atomic I'm not sure what value that has.
Re:Things UNIX can do atomically by geocar on Wednesday January 06, 2010 @03:47PM (#1035710)
This is a great one: Under POSIX, any write() to a fifo that has at least PIPE_BUF free is atomic.

There's a neat trick I'd like to add that takes advantage of this: Multiple clients can use a message whose size divides evenly into PIPE_BUF without any possibility of interleave, and so they do not need to lock.

    int n=sizeof(struct message);
    struct message m[n/PIPE_BUF];
    assert(sizeof(m)==PIPE_BUF);
    if(pipe(fds)==-1)abort();
    for(i=0;i<cpus;i++){if(!fork())child(fds[1]);}
    while(r=read(fds[0],m,PIPE_BUF)){for(i=r/n-1;i>=0;--i)handle(m+i);}
Each child can write entire messages, without locking and without interleaving, so long as sizeof(struct message)*n is exactly PIPE_BUF.

Btw, your pipe(&pipefd) should've been pipe(pipefd) if pipefd is an array of 2 int

Re:Things UNIX can do atomically by sophacles on Wednesday January 06, 2010 @05:05PM (#1035895)
Makes logging things easier, and in correct order!