0xbe5077ed
0xbe5077ed

Reputation: 4775

POSIX or Linux way of getting unique ID of shell process

I'm writing a simple command-line utility program and would would like to be able to get some kind of globally unique identifier for the parent process (i.e. the shell in which the command is run).

PID is not enough for me, because over time there is a possibility that two PID values will collide.

My use case is as follows: I want to store "session" data from running the command-line utility that persists across all instances of the utility that are run within the same shell process. I don't want this data shared with other shell instances. I want some kind of identifier that will allow me to perform that association without the possibility of collision.

I've ruled out PID and PID+tty. What would be nice would be a way to query process start date/time so my unique ID would be PID+tty+start date/time...

Any ideas gratefully accepted!

Upvotes: 5

Views: 2017

Answers (1)

Tobias Stoeckmann
Tobias Stoeckmann

Reputation: 152

Unique Files

I recommend to use a file-based approach. Unique files, especially unique temporary files, are needed in many situations, so you can use a tool for exactly this purpose, mktemp:

$ mktemp -t identifier.XXXXXXXXXX
/tmp/identifier.yaJMl0cBnK

If you execute this command in your parent shell, you will get a name of a newly created file, created in a guaranteed unique manner. As you can see, the suffix of X's (at least 3) is replaced with random content, so if the target file is already in use, mktemp has many chances to create an alternative.

To avoid pollution, make sure that your parent shell removes the file when your work is done.

Now you can either write the date/time into the file or adjust the identifier part. It really depends on what you like more.

Unique Sessions

As figured out in comments, the creation of a temporary file is not always desired. In fact, the use of mktemp cannot be considered POSIX-compliant, because the utility mktemp(1) is not covered in the standard.

Another approach would be the utilization of the "session id" (technically correct: "process id of the session leader"). The question specifically states that the parent process is a shell. Shells become session leaders in order to manage their process groups. You can see the session id by calling ps with -o session, e.g. ps -o pid,session,cmd.

The session id remains as long as at least one process is still inside that session. You can safely assume that the session id is unique to your group of programs and unique on your system. This is also true if the parent shell terminates. Your programs become orphaned, but remain in their session. The session is only destroyed (and session id released) if the last program terminates.

In C/C++, you can retrieve the session id of your process by calling getsid(0), which is covered by POSIX.

Upvotes: 4

Related Questions