Tracking your local tasks using the PID

It is usual in the Computational Chemistry workflow to have multiple simultaneous tasks running. Like the Brazilian SDumont, supercomputers have queue systems, like the SLURM Workload Manager, which also turn the tracking of your running jobs easier. On the other hand, run multiple jobs in your local machine could be very hard to track, mostly if they are related to the same command, like python3, for example.

To improve my productivity, I developed two useful Bash functions which can help in handle multiple tasks.

Function jobPID

The jobPID function gets the PID (‘process ID‘) from a Terminal command by the GNU jobs command. Then, it creates an ASCII file called job.pid, which contains only the PID number.

Bash Version (Linux)

jobPID() { terminal_command=\"$*\" pid_file=\'job.pid\' ((${terminal_command}) & jobs -p >${pid_file})}

Zsh Version (MacOS)

jobPID() { terminal_command=\"$*\" pid_file=\'job.pid\' ((eval ${terminal_command}) & echo $! > ${pid_file})}

How to use jobPID?

To use jobPID, you just need to include the jobPID before the Terminal command you want to track.

~$ jobPID <Terminal command>

Function checkPID

The checkPID function is an auxiliary function that can easily check a PID from a job.pid file in the actual directory. It gets the PID number and tests if it is still running using a combination of the ps, which lists the current processes in your machine, and the grep, which searches for the PID number in this list. Additionally, it removes the temporary job.pid file if its related task is completed, cleaning up your work directory.

Bash Version (Linux)

checkPID() { pid_file=\'job.pid\' if [ -f ${pid_file} ]; then pid_num=`cat ${pid_file} if (ps -A|grep -q ${pid_num}); then echo \"Job PID:${pid_num} still running...\" else echo \"Job PID:${pid_num} completed!\" rm ${pid_file} fi fi}

Zsh Version (MacOS)

checkPID() { pid_file=\'job.pid\' if [ -f ${pid_file} ]; then pid_num=$(< ${pid_file}) if (ps -A|awk \'{print $1}\'|grep -q ${pid_num}); then echo \"Job PID:${pid_num} still running...\" else echo \"Job PID:${pid_num} completed!\" rm ${pid_file} fi fi}

How to install these functions in your Terminal?

All you have to do is add these functions in your Terminal initialization script ($HOME/.bashrc for Bash and $HOME/.zshrc for Zsh)!

I hope you enjoy it!

Best regards and stay safe!

Comments are closed.