我们可以使用&在后台执行bash,例如,livereload &、php -S localhost:8000 &,但是如果我离开了终端而忘记了终止过程,它将一直在那里直到重新启动,我可以使用命令jobs检查哪个bash是由我执行的,但是如果我打开一个新的终端或再次登录,jobs -l将是空的,当再次登录时,谁会发现它。
发布于 2016-01-20 04:08:22
如果使用&,这会将进程放在后台;但是,该进程仍然附加到特定的终端(更具体地说,命令在其中执行的活动shell )。当您退出该终端(或退出该shell)时,该进程将被终止。(见:https://unix.stackexchange.com/questions/86247/what-does-ampersand-mean-at-the-end-of-a-shell-script-line)
当进程分叉子进程,而该子进程现在由init拥有时,进程在退出该外壳时不会被终止的情况(PPID 1)。这很可能是livereload &的情况。
还可以通过点击Ctrl-Z将当前运行在前台的进程放置到后台,这将使您回到您的shell,同时挂起(而不是杀死)进程,然后键入bg,然后在后台继续执行该进程。
当您运行了<cmd> &,或者当您使用Ctrl-z和bg将进程移到后台时,您可以通过键入fg将其带回前台。此时,您将能够使用Ctrl-c杀死它。
但是,通常情况下,要查找已分离的进程,可以使用
ps -f | grep <name of the command> | grep -v grep如果您想查看其他用户的进程,您需要添加-e和-a,如下所示
ps -eaf | grep <name of the command> | grep -v grep或
ps aux | grep <name of the command> | grep -v grep(注意:grep -v grep部分将删除执行grep命令的进程。)
现在,要将进程从shell中分离出来,可以使用以下几种实用工具之一:
screennohup --如在nohup <CMD> &中,它将捕获进程的挂起信号(有关更多细节,请参见:What's the difference between nohup and ampersand )。tmux (见:https://superuser.com/questions/236158/tmux-vs-screen)编辑:如果您不记得您在后台放置了什么,并且这些进程已经脱离当前的shell (或者可能正在捕捉挂起信号),则可以从history中获取grep,并查看是否可以在活动进程中找到
history | grep "&$" | sed "s/&//g" | sed "s/^[ \t]*[0-9]*//g" | sed "s/^[ \t]*//g" | xargs -d '\n' pgrep这条直线的工作方式是它是grep的历史,在它的末尾有一个&,例如,
898 my_script & # <----- you'll only see lines like this
899 ls
900 sleep 10000 & # <----- you'll only see lines like this
901 pwd然后将其传递给sed,并移除尾随符号。它再通过sed将其传递两次,以删除起始号(即历史上命令的编号)并启动空格。然后使用pgrep对活动进程进行处理。对我来说,sleep 10000 &的输出是90448
mgr@tesla:~$ ps aux | grep sleep
mgr 91040 0.0 0.0 2434836 756 s002 S+ 9:37AM 0:00.00 grep sleep
mgr 90448 0.0 0.0 2434820 340 s002 S 9:24AM 0:00.00 sleep 100000
mgr@tesla:~$ history | grep "&$" | sed "s/&//g" | sed "s/^[ \t]*[0-9]*//g" | sed "s/^[ \t]*//g" | xargs pgrep
90448现在,您甚至可以再次将其导入xargs以终止这些进程(如果您确信它们是正确的)。如果要验证,只需运行
mgr@tesla:~$ ps -p 90448 -o comm=
sleep或
mgr@tesla:~$ ps aux | grep 90448 | grep -v grep
mgr 90448 0.0 0.0 2434820 340 s002 S 9:24AM 0:00.00 sleep 100000https://stackoverflow.com/questions/34891334
复制相似问题