getpid() or something similar

John Meacham john@repetae.net
Thu, 22 May 2003 08:21:37 -0700


On Thu, May 22, 2003 at 12:05:46PM +0200, Peter Simons wrote:
> Simon Marlow writes:
>  > Even using a ProcessID doesn't guarnatee uniqueness [...]
> Why not? If I use the file only temporarily (it is gone once the
> process terminates), something like /tmp/foo.<pid> will be unique, for
> all I can tell. 
standard procedure is to integrate: 
1) your hostname
2) the current time
3) the pid
4) an incrementing counter
5) your program name

into the name. this should be guarenteed to be unique. the reason to
include your hostname is that you may be on an NFS filesystem where
different systems will be using the same PID at the same time. the
reason to use the current time is pid's are reused. and you need the
counter to create multiple temporary files within a second of each
other. the program name is because other apps may use this scheme.


>  > The right way to do this is to try to open it for writing, and try
>  > a different name if the open fails.
> 
> Unfortunately, this approach features a race condition because POSIX
> has no notion of mandatory file locking. I'd really rather avoid this,
> if I can.
> 
> Is there no other way? And one that works across different compilers?

mandatory locks arn't needed. (and they are a common extension to the
fcntl(2) locking mechanism anyway, at least I do not know of a system
which doesn't support them)

open(..., O_RDWR | O_CREAT | O_EXCL, 0600);
is what you want, (wrapped in haskell of course) it will create the file
if it doesnt exit (O_CREAT) but if it already does exist then it will
return an error (EEXIST). this check is done ATOMICALLY, meaning there
is no race condition. of course, if you follow the above advice when
choosing a name then this is unlikely to be an issue unless a program
tries to step on your toes.
        John

-- 
---------------------------------------------------------------------------
John Meacham - California Institute of Technology, Alum. - john@foo.net
---------------------------------------------------------------------------