#!/bin/bash
if [ -z "$(pgrep some_process)" ]; then
echo "some_process not running.. Starting.."
echo "passwd" | su - user
nohup ./some_process &
echo "PS : $(ps ax | grep some process)"
echo "passwd_of_original_user" | su - original_user
echo "PS : $(ps ax | grep some process)" #some_process is already not running at this line
else
echo "Some_process already running.."
fi
Now the problem is that the "some_process" should run continuously, yet at the second check of running processes (the line with a comment in code) it is already not running.
From what I googled, the "nohup" command should keep it running even after logging out of the system, but apparently it doesn't.
I dont know what I'm doing wrong, any help will be appreciated
What does "some process" do? Is it short lived by definition? Any error msgs? Does your grep work correctly (the "_" is missing in the search pattern)? Why do you change from pgrep to grep ? I think by switching to and fro between users you're closing your shell/script...
Some_process isnt short lived. It runs continuously until user tells it to stop.
The greps are working correctly (the first one displays the process, I've obviously changed the code to be easier to read for people here, so missing "_" is not a real problem).
As for closing my shell/script - from what I understand that's exactly what
nohup
is for - keep the process running even after logout, user change, shell close, yet somehow it seems to be not working
I don't think the below is the correct way to run some_process as user
echo "some_process not running.. Starting.."
echo "passwd" | su - user
nohup ./some_process &
echo "PS : $(ps ax | grep some process)"
echo "passwd_of_original_user" | su - original_user
echo "PS : $(ps ax | grep some process)" #some_process is already not running at this line
Instead try something like this:
echo "some_process not running.. Starting.."
echo "passwd" | su - user -c "nohup ./some_process &"
echo "PS : $(ps ax | grep some process)" #some_process is already not running at this line
However su on many systems will also refuse to accept passwords from a pipe issuing an error like standard in must be a tty .
sudo is usually a better choice in this situation, as the requiretty constraint can be relaxed for some_process or user .
If as I suspect you have little admin control over host you may be forced to run another expect script to get some_process running as user
Thanks Chubler, that code is indeed the correct way as I just checked
echo "passwd" | su - user -c "nohup ./some_process &"
Although I couldnt check it on the original "some_process" today, it seemed to click with "some_another_process" I sure hope it'll also work for the original one or I'll get sad