Start background process from .bashrc

2020-02-29 07:46发布

问题:

I realize that this might be a stupid issue but I can't solve it for hours even if digged stackoverflow site and google throughly.

Here is the base code in .bashrc to start gkrellm once I am logged into shell

if ps ax | grep -v grep | grep gkrellm > /dev/null
then
    echo "gkrellm is already running"
else
    command gkrellm &
fi

I already used to try

...
else
    nohup gkrellm &
fi
...

and

...
else
    gkrellm
    $GK_PID=`pidof gkrellm`
    disown -h $GK_PID
fi
...

gkrellm is properly put as background job and I can use shell (as expected). BUT I still have gkrellm exiting once I press Ctrl-c even if I start other apps from that same shell. How do I prevent gkrellm from closing on Ctrl-c press?

Just in case. I am using PuTTY clone called KiTTY but believe that's not it's issue.

Thanks for help!

回答1:

Try replacing "nohup gkrellm &" with this:

screen -S gkrellm -d -U -m gkrellm

This will start a detached screen session running gkrellm, and it won't care about the current shell session. I'm not sure if starting it from .bashrc is the best solution though, it would make more sense to use your window manager's autostart features.

Edit: Not sure if I read the question correctly, are you using KiTTY to connect to a linux host and running gkrell remotely through X forwarding? If that is the case, you obviously can't use window manager features. :)



回答2:

using bash (disown and &>/dev/null)
you need to run the app in the bg (gkrellm &) and then disown it

if ps -C gkrellm -o user | grep "$LOGNAME" &>/dev/null 
then echo "gkrellm is already running"
else gkrellm & disown
fi

if you want to be more portable and use posix sh
you will need to use nohup (part of coreutils and POSIX)
and also background it (nohup cmd &)
you'd also use .profile instead of .bashrc

if ps -C gkrellm -o user | grep "$LOGNAME" 2>/dev/null 1>&2
then echo "gkrellm is already running"
else nohup gkrellm &
fi

other approaches would include - as @Pontus answered - using tools like dtach, screen or tmux, where the command is executed in a detached environment.

by Pontus:
it would make more sense to use your window manager's autostart features

indeed :) as afaik gkrellm is a GUI app, it's better to autostart it, either using .xinitrc (if your login manager supports it), or your window manager's autostart facilities.



回答3:

Almost forgot about this issue and answering my own question after found a working solution long ago ;) Follow works great in my .bashrc for years

mygkrellm()
{
    if pidof -x "gkrellm" >/dev/null; then
    echo "Gkrellm is already running. Go to shell!"       
    else
    nohup "/usr/bin/gkrellm" &
    fi
}


标签: bash putty