Portable PID routine

I need a quick routine in C that returns a string equal to the
process ID or, if under a non-unix system (with some kind of
standard facility to check - maybe a defined token) a random
number or something equivalent.

Obviously it would be impossible to check all possible platforms, but generally I'm talking about standard unix flavors verses windows platforms - which I understand do not have process IDs.  The idea is to create a random string that can be used for a temporary filename in either unix or windows.

The shell might be something like this:

char *pid_string(void) {
  static char pvalue[MAX_LENGTH]="\0";

#ifdef (whatever to determine if non-unix)

(routine to generate a random string for systems where
we can't grab a PID)


(routine to grab PID and stuff in a string - how portable
can this be? - I don't want to shell and reference $$ - want
to do it from C if possible)



Thanks very much for any assistance!
Who is Participating?
imladrisConnect With a Mentor Commented:
Wouldn't it be better (and simpler) to use tempnam or tmpnam?

char *tempnam(char *dir,char *prefix);
char *tmpnam(char *string);

The tmpnam function generates a temporary file name that can be used to open a temporary file without overwriting an existing file.

The tempnam function allows the program to create a temporary file name for use in another directory.
maabuAuthor Commented:
I'm not familiar with the routine.  How portable is this?
In the Microsoft manual I checked "tmpnam" is listed as ANSI standard. tempnam is available in all environments but not ANSI standard.
maabuAuthor Commented:
This does the job - I've tested it on multiple platforms and you are correct!  Thanks very much.

One quick question: is there a #define token that can be used to reliably id OS and platforms?
There is no standard one that I am aware of.

In fact, it is my recollection that creating a define that indicates which OS is being used is one of the canonical examples for conditional compilation.
All Courses

From novice to tech pro — start learning today.