Closed. This question is not about programming or software development. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed last month.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm working on a Linux machine through SSH (Putty). I need to leave a process running during the night, so I thought I could do that by starting the process in background (with an ampersand at the end of the command) and redirecting stdout to a file.
To my surprise, that doesn't work. As soon as I close the Putty window, the process is stopped.
How can I prevent that from happening??
Check out the "nohup" program.
I would recommend using GNU Screen. It allows you to disconnect from the server while all of your processes continue to run. I don't know how I lived without it before I knew it existed.
When the session is closed the process receives the SIGHUP signal which it is apparently not catching. You can use the nohup command when launching the process or the bash built-in command disown -h after starting the process to prevent this from happening:
> help disown
disown: disown [-h] [-ar] [jobspec ...]
By default, removes each JOBSPEC argument from the table of active jobs.
If the -h option is given, the job is not removed from the table, but is
marked so that SIGHUP is not sent to the job if the shell receives a
SIGHUP. The -a option, when JOBSPEC is not supplied, means to remove all
jobs from the job table; the -r option means to remove only running jobs.
daemonize? nohup? SCREEN? (tmux ftw, screen is junk ;-)
Just do what every other app has done since the beginning -- double fork.
# ((exec sleep 30)&)
# grep PPid /proc/`pgrep sleep`/status
PPid: 1
# jobs
# disown
bash: disown: current: no such job
Bang! Done :-) I've used this countless times on all types of apps and many old machines. You can combine with redirects and whatnot to open a private channel between you and the process.
Create as coproc.sh:
#!/bin/bash
IFS=
run_in_coproc () {
echo "coproc[$1] -> main"
read -r; echo $REPLY
}
# dynamic-coprocess-generator. nice.
_coproc () {
local i o e n=${1//[^A-Za-z0-9_]}; shift
exec {i}<> <(:) {o}<> >(:) {e}<> >(:)
. /dev/stdin <<COPROC "${#}"
(("\$#")&) <&$i >&$o 2>&$e
$n=( $o $i $e )
COPROC
}
# pi-rads-of-awesome?
for x in {0..5}; do
_coproc COPROC$x run_in_coproc $x
declare -p COPROC$x
done
for x in COPROC{0..5}; do
. /dev/stdin <<RUN
read -r -u \${$x[0]}; echo \$REPLY
echo "$x <- main" >&\${$x[1]}
read -r -u \${$x[0]}; echo \$REPLY
RUN
done
and then
# ./coproc.sh
declare -a COPROC0='([0]="21" [1]="16" [2]="23")'
declare -a COPROC1='([0]="24" [1]="19" [2]="26")'
declare -a COPROC2='([0]="27" [1]="22" [2]="29")'
declare -a COPROC3='([0]="30" [1]="25" [2]="32")'
declare -a COPROC4='([0]="33" [1]="28" [2]="35")'
declare -a COPROC5='([0]="36" [1]="31" [2]="38")'
coproc[0] -> main
COPROC0 <- main
coproc[1] -> main
COPROC1 <- main
coproc[2] -> main
COPROC2 <- main
coproc[3] -> main
COPROC3 <- main
coproc[4] -> main
COPROC4 <- main
coproc[5] -> main
COPROC5 <- main
And there you go, spawn whatever. the <(:) opens an anonymous pipe via process substitution, which dies, but the pipe sticks around because you have a handle to it. I usually do a sleep 1 instead of : because its slightly racy, and I'd get a "file busy" error -- never happens if a real command is ran (eg, command true)
"heredoc sourcing":
. /dev/stdin <<EOF
[...]
EOF
This works on every single shell I've ever tried, including busybox/etc (initramfs). I've never seen it done before, I independently discovered it while prodding, who knew source could accept args? But it often serves as a much more manageable form of eval, if there is such a thing.
nohup blah &
Substitute your process name for blah!
Personally, I like the 'batch' command.
$ batch
> mycommand -x arg1 -y arg2 -z arg3
> ^D
This stuffs it in to the background, and then mails the results to you. It's a part of cron.
As others have noted, to run a process in the background so that you can disconnect from your SSH session, you need to have the background process properly disassociate itself from its controlling terminal - which is the pseudo-tty that the SSH session uses.
You can find information about daemonizing processes in books such as Stevens' "Advanced Network Program, Vol 1, 3rd Edn" or Rochkind's "Advanced Unix Programming".
I recently (in the last couple of years) had to deal with a recalcitrant program that did not daemonize itself properly. I ended up dealing with that by creating a generic daemonizing program - similar to nohup but with more controls available.
Usage: daemonize [-abchptxV][-d dir][-e err][-i in][-o out][-s sigs][-k fds][-m umask] -- command [args...]
-V print version and exit
-a output files in append mode (O_APPEND)
-b both output and error go to output file
-c create output files (O_CREAT)
-d dir change to given directory
-e file error file (standard error - /dev/null)
-h print help and exit
-i file input file (standard input - /dev/null)
-k fd-list keep file descriptors listed open
-m umask set umask (octal)
-o file output file (standard output - /dev/null)
-s sig-list ignore signal numbers
-t truncate output files (O_TRUNC)
-p print daemon PID on original stdout
-x output files must be new (O_EXCL)
The double-dash is optional on systems not using the GNU getopt() function; it is necessary (or you have to specify POSIXLY_CORRECT in the environment) on Linux etc. Since double-dash works everywhere, it is best to use it.
You can still contact me (firstname dot lastname at gmail dot com) if you want the source for daemonize.
However, the code is now (finally) available on GitHub in my SOQ (Stack
Overflow Questions) repository as file daemonize-1.10.tgz in the
packages
sub-directory.
For most processes you can pseudo-daemonize using this old Linux command-line trick:
# ((mycommand &)&)
For example:
# ((sleep 30 &)&)
# exit
Then start a new terminal window and:
# ps aux | grep sleep
Will show that sleep 30 is still running.
What you have done is started the process as a child of a child, and when you exit, the nohup command that would normally trigger the process to exit doesn't cascade down to the grand-child, leaving it as an orphan process, still running.
I prefer this "set it and forget it" approach, no need to deal with nohup, screen, tmux, I/o redirection, or any of that stuff.
On a Debian-based system (on the remote machine)
Install:
sudo apt-get install tmux
Usage:
tmux
run commands you want
To rename session:
Ctrl+B then $
set Name
To exit session:
Ctrl+B then D
(this leaves the tmux session). Then, you can log out of SSH.
When you need to come back/check on it again, start up SSH, and enter
tmux attach session_name
It will take you back to your tmux session.
If you use screen to run a process as root, beware of the possibility of privilege elevation attacks. If your own account gets compromised somehow, there will be a direct way to take over the entire server.
If this process needs to be run regularly and you have sufficient access on the server, a better option would be to use cron the run the job. You could also use init.d (the super daemon) to start your process in the background, and it can terminate as soon as it's done.
nohup is very good if you want to log your details to a file. But when it goes to background you are unable to give it a password if your scripts ask for. I think you must try screen. its a utility you can install on your linux distribution using yum for example on CentOS yum install screen then access your server via putty or another software, in your shell type screen. It will open screen[0] in putty. Do your work. You can create more screen[1], screen[2], etc in same putty session.
Basic commands you need to know:
To start screen
screen
To create next screen
ctrl+a+c
To move to next screen you created
ctrl+a+n
To detach
ctrl+a+d
During work close your putty. And next time when you login via putty type
screen -r
To reconnect to your screen, and you can see your process still running on screen. And to exit the screen type #exit.
For more details see man screen.
Nohup allows a client process to not be killed if a the parent process is killed, for argument when you logout. Even better still use:
nohup /bin/sh -c "echo \$\$ > $pidfile; exec $FOO_BIN $FOO_CONFIG " > /dev/null
Nohup makes the process you start immune to termination which your SSH session and its child processes are kill upon you logging out. The command i gave provides you with a way you can store the pid of the application in a pid file so that you can correcly kill it later and allows the process to run after you have logged out.
Use screen. It is very simple to use and works like vnc for terminals.
http://www.bangmoney.org/presentations/screen.html
There's also the daemon command of the open-source libslack package.
daemon is quite configurable and does care about all the tedious daemon stuff such as automatic restart, logging or pidfile handling.
If you're willing to run X applications as well - use xpra together with "screen".
i would also go for screen program (i know that some1 else answer was screen but this is a completion)
not only the fact that &, ctrl+z bg disown, nohup, etc. may give you a nasty surprise that when you logoff job will still be killed (i dunno why, but it did happened to me, and it didn't bother with it be cause i switched to use screen, but i guess anthonyrisinger solution as double forking would solve that), also screen have a major advantage over just back-grounding:
screen will background your process without losing interactive control to it
and btw, this is a question i would never ask in the first place :) ... i use screen from my beginning of doing anything in any unix ... i (almost) NEVER work in a unix/linux shell without starting screen first ... and i should stop now, or i'll start an endless presentation of what good screen is and what can do for ya ... look it up by yourself, it is worth it ;)
Append this string to your command: >&- 2>&- <&- &. >&- means close stdout. 2>&- means close stderr. <&- means close stdin. & means run in the background. This works to programmatically start a job via ssh, too:
$ ssh myhost 'sleep 30 >&- 2>&- <&- &'
# ssh returns right away, and your sleep job is running remotely
$
Accepted answer suggest using nohup. I would rather suggest using pm2. Using pm2 over nohup has many advantages, like keeping the application alive, maintain log files for application and lot more other features. For more detail check this out.
To install pm2 you need to download npm. For Debian based system
sudo apt-get install npm
and for Redhat
sudo yum install npm
Or you can follow these instruction.
After installing npm use it to install pm2
npm install pm2#latest -g
Once its done you can start your application by
$ pm2 start app.js # Start, Daemonize and auto-restart application (Node)
$ pm2 start app.py # Start, Daemonize and auto-restart application (Python)
For process monitoring use following commands:
$ pm2 list # List all processes started with PM2
$ pm2 monit # Display memory and cpu usage of each app
$ pm2 show [app-name] # Show all informations about application
Manage processes using either app name or process id or manage all processes together:
$ pm2 stop <app_name|id|'all'|json_conf>
$ pm2 restart <app_name|id|'all'|json_conf>
$ pm2 delete <app_name|id|'all'|json_conf>
Log files can be found in
$HOME/.pm2/logs #contain all applications logs
Binary executable files can also be run using pm2. You have to made a change into the jason file. Change the "exec_interpreter" : "node", to "exec_interpreter" : "none". (see the attributes section).
#include <stdio.h>
#include <unistd.h> //No standard C library
int main(void)
{
printf("Hello World\n");
sleep (100);
printf("Hello World\n");
return 0;
}
Compiling above code
gcc -o hello hello.c
and run it with np2 in the background
pm2 start ./hello
I used screen command. This link has detail as to how to do this
https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/#starting
On systemd/Linux, systemd-run is a nice tool to launch session-independent processes.
I'm wanting to open a terminal from a Python script (not one marked as executable, but actually doing python3 myscript.py to run it), have the terminal run commands, and then keep the terminal open and let the user type commands into it.
EDIT (as suggested): I am primarily needing this for Linux (I'm using Xubuntu, Ubuntu and stuff like that). It would be really nice to know Windows 7/8 and Mac methods, too, since I'd like a cross-platform solution in the long-run. Input for any system would be appreciated, however.
Just so people know some useful stuff pertaining to this, here's some code that may be difficult to come up with without some research. This doesn't allow user-input, but it does keep the window open. The code is specifically for Linux:
import subprocess, shlex;
myFilePathString="/home/asdf asdf/file.py";
params=shlex.split('x-terminal-emulator -e bash -c "python3 \''+myFilePathString+'\'; echo \'(Press any key to exit the terminal emulator.)\'; read -n 1 -s"');
subprocess.call(params);
To open it with the Python interpreter running afterward, which is about as good, if not better than what I'm looking for, try this:
import subprocess, shlex;
myFilePathString="/home/asdf asdf/file.py";
params=shlex.split('x-terminal-emulator -e bash -c "python3 -i \''+myFilePathString+'\'"');
subprocess.call(params);
I say these examples may take some time to come up with because passing parameters to bash, which is being opened within another command can be problematic without taking a few steps. Plus, you need to know to use to quotes in the right places, or else, for example, if there's a space in your file path, then you'll have problems and might not know why.
EDIT: For clarity (and part of the answer), I found out that there's a standard way to do this in Windows:
cmd /K [whatever your commands are]
So, if you don't know what I mean try that and see what happens. Here's the URL where I found the information: http://ss64.com/nt/cmd.html
Is there any possible way to implement a sudo context manager which runs the enclosing scope as another user, using the sudoers system?
system('whoami') # same result as echo $USER
with sudo():
system('whoami') # root
I doubt that the sudo(8) executable will help me here, but maybe there is some C-level interface that I can bind to?
Motivation: I can almost port this shell script entirely to python without even any subprocesses, except I currently have to system('sudo sh -c "echo %i > /dev/thatfile"' % value). It would be so elegant if I could with sudo(), open('/dev/thatfile', 'w') as thatfile: thatfile.write(str(value)).
I suspect this is not possible in any simple way. Programs that escalate their permissions like sudo must have a flag set in their file system permissions (the is the "setuid" bit) in order to tell the operating system to run them as a different user than the one that started them up. Unless you want your whole Python interpreter to be setuid root, there's no direct way to do something equivalent for just some small part of your Python code.
It might conceivably be possible to implement a sudo style context manager not by making your regular Python code run privileged, but rather by temporarily replacing the library code that makes various OS calls (such as opening a file) with some kind of proxy that connects it to a setuid helper program. But it would be a lot of work to get something like that to work, and a lot more work to make sure it was secure enough to use anywhere in production.
An idea, if you don't like your current solution of using a shell script from a system call: Write the file using regular Python code, with your regular user permissions. Then chown it (and move it, if necessary) with a sudo call.
Is there a way on Linux to check what a running Python daemon process is doing? That is, without instrumenting the code and without terminating it? Preferably I'd like to get the name of the module and the line number in it that is currently running.
Conventional debugging tools such as strace, pstack and gdb are not very useful for Python code. Most stack frames just contain functions from the interpreter code like PyEval_EvalFrameEx and and PyEval_EvalCodeEx, it doesn't give you any hint on were in the .py-file the execution is.
Some of the answers in Showing the stack trace from a running Python application are applicable in this situation:
pyrasite (this was the one that worked for me):
$ sudo pip install pyrasite
$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
$ sudo pyrasite 16262 dump_stacks.py # dumps stacks to stdout/stderr of the python program
pyringe
pydbattach - couldn't get this to work, but the repository https://github.com/albertz/pydbattach contains pointer to other tools
pstack reportedly prints the python stack on Solaris
py-spy (https://github.com/benfred/py-spy) has a few useful tools for inspecting running Python processes. In particular, py-spy dump will print a stack trace (including function, file, and line) for every thread.
winpdb allows you to attach to a running python process, but to do this, you must start the python process this way:
rpdb2 -d -r script.py
Then, after setting a password:
A password should be set to secure debugger client-server communication.
Please type a password:mypassword
you could launch winpdb to File>Attach to (or File>Detach from) the process.
on POSIX systems like Linux, you can use good old GDB, see
https://t37.net/debug-a-running-python-process-without-printf.html
and
https://wiki.python.org/moin/DebuggingWithGdb
There's also the excellent PyCharm IDE (free community version available) that can attach to a running Python process right from within the IDE, using Pdb 4 under the hood, see this blog entry:
http://blog.jetbrains.com/pycharm/2015/02/feature-spotlight-python-debugger-and-attach-to-process/
lptrace does exactly that. It allows you to attach to a running Python process and show currently executing functions, like strace does for system calls. You can call it like this:
vagrant#precise32:/vagrant$ sudo python lptrace -p $YOUR_PID
fileno (/usr/lib/python2.7/SocketServer.py:438)
meth (/usr/lib/python2.7/socket.py:223)
fileno (/usr/lib/python2.7/SocketServer.py:438)
meth (/usr/lib/python2.7/socket.py:223)
...
Note that it requires gdb to run, which isn't available on every server machine.
You can use madbg (by me). It is a python debugger that allows you to attach to a running python program and debug it in your current terminal. It is similar to pyrasite and pyringe, but newer, doesn't require gdb, and uses IPython for the debugger (which means colors and autocomplete).
To see the stack trace of a running program, you could run:
madbg attach <pid>
And in the debugger shell, enter:
bt
It's possible to debug Python with gdb. See Chapter 22: gdb Support in the Python Developer’s Guide.
For example, on Debian with Python 3.7:
# apt-get update -y && apt-get install gdb python3.7-dbg
# gdb
(gdb) source /usr/share/gdb/auto-load/usr/bin/python3.7-gdb.py
(gdb) attach <PID>
(gdb) py-bt
You can also use satella to do this. A nice side effect will be that every local variable in every stack frame will be printed out. The code would be:
from satella.instrumentation import Traceback
import sys
for frame_no, frame in sys._current_frames().items():
sys.stderr.write("For stack frame %s" % (frame_no,))
tb = Traceback(frame)
tb.pretty_print()
sys.stderr.write("End of stack frame dump\n")