News for hackers. Stuff that matters.
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

There are no comments on this comment yet.