Reputation: 1860
I do my backups with rsnapshot which creates a lockfile with the process pid inside. Now I would like to make a backup from the rsnapshots backup, so I´m looking for a way to create this lockfile for the second/external backup.
The shell script should like this:
How can I get the PID and save it as a rsnapshot lockfile ?
Upvotes: 5
Views: 25360
Reputation: 319
For any application, you can find its Process ID using the Unix shell itself, using ps. Example below is a very reduced list from ps. PS will show you not only the PID, but also the owner, as well as the Parent Process ID (as in which process started this particular process.)
userX# ps -ef | more
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 Oct19 ? 00:00:00 /sbin/init
root 2 0 0 Oct19 ? 00:00:00 [kthreadd]
root 3 2 0 Oct19 ? 00:00:02 [migration/0]
root 4 2 0 Oct19 ? 00:04:48 [ksoftirqd/0]
root 5 2 0 Oct19 ? 00:00:00 [migration/0]
root 6 2 0 Oct19 ? 00:00:00 [watchdog/0]
...
root 27 2 0 Oct19 ? 00:00:00 [pm]
root 28 2 0 Oct19 ? 00:00:00 rsnapshot
root 29 2 0 Oct19 ? 00:00:00 [xenbus]
Now let's start finding which Process is interesting to us. I am not familiar with rsnapshot, so I've put dummy data in the examples.
userX# ps -ef | grep rsnapshot
root 28 2 0 Oct19 ? 00:00:00 rsnapshot
ec2-user 7233 1497 0 11:32 pts/0 00:00:00 grep rsnapshot
Note that it does not give you the "header" information, only matching lines, thanks to grep. Your second "column" is the PID. Noteworthy: ps shows every process, including the grep you just ran. Your commands/scripts need to be wary of this and strip out these items. I will use awk in the next example to do just that.
And now to expand further, getting the PID into a file. We need to confirm we have a PID, and if so, create the command to create the lock file:
userX# ps -ef | grep rsnapshot | awk '$0!~/grep/ && $2~/[0-9]/{print "echo "$2" > rsnapshot.lck"}'
echo 28 > rsnapshot.lck
If no PID for rsnapshot exists, then there will be no output. As writtent, awk will review each line, and if it does not contain the string "grep" AND there is any digit [0-9] in the second field, then print the command to be run - but not actually run the command.
The final step is to invoke the command, from the awk output.
userX# ps -ef | grep rsnapshot | awk '$0!~/grep/ && $2~/[0-9]/{print "echo "$2" > rsnapshot.lck"}' | sh
Adding "| sh" causes all output to be invoked as a command. If awk does not find rsnapshot, then there is no command to run.
Upvotes: 2
Reputation: 10663
The PID is stored in $$
Like
echo $$ > thisscriptpidfile
Upvotes: 8