程序后台运行、恢复前台nohup
# nohup+&后台运行
https://blog.csdn.net/hl449006540/article/details/80216061
现在我们要执行一个程序
ping 127.0.0.1
也可以是./hello_world
或者./test
执行
ping 127.0.0.1 &
程序会后台运行,但是继续输出到shell终端, Ctrl+C也不能给程序发送信号。当shell终端关掉时,程序收到SIGHUP
信号,就停止运行了。执行
nohup ping 127.0.0.1
程序会前台运行,生成nohup.out文件,但是文件里啥也没有。关闭shell程序会继续运行。 nohup的作用是就是忽略SIGHUP
信号,把标准输入重定向到'/dev/null', 把标准输出重定向到'nohup.out'执行
nohup ping 127.0.0.1 &
程序会后台运行,关闭shell也没事,并且会输出结果到当前目录的nohup.out。这个就是正确的程序后台运行方式。
# nohup+&后台运行时的程序输出保存
执行
nohup ping 127.0.0.1 &
, 输出保存在当前目录的nohup执行
nohup ping 127.0.0.1 >ping.log 2>&1 &
, 输出保存至ping.log
。2>&1
表示将标准错误重定向到到标准输出。 注意这里2>&1
要在后面执行
nohup ping 127.0.0.1 >/dev/null 2>&1 &
, 输出不保存。 就是将上面的ping.log改成ping.log
。/dev/null
是linux上一个黑洞文件,相当于空。
# 前台程序转后台,Ctrl+Z暂停程序运行,以及后台程序恢复前台运行
SINKILL停止信号和SIGSTOP暂停信号是不能被捕捉和忽略的。
Ctrl+Z
向shell前台中正在运行的程序发送'SIGSTOP'暂停信号,程序将暂停运行,并被放到后台。
kill -SIGCONT pid
向程序发送继续运行的消息,程序会继续在后台运行;
编译并运行下面的程序 main.c:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
sighandler_t Signal(int signum, sighandler_t handler) {
struct sigaction action, old_action;
action.sa_handler = handler;
sigemptyset(&action.sa_mask);
action.sa_flags = SA_RESTART;
if(sigaction(signum, &action, &old_action) < 0) {
fprintf(stderr, "%s: %s\n", "sigaction error", strerror(errno));
exit(0);
}
return old_action.sa_handler;
}
void signal_handler(int signum) {
puts("received signal\n");
}
int main(int argc, char *argv[]) {
// signal(SIGINT, signal_handler);
Signal(SIGINT, signal_handler);
while(1) {
usleep(1000*1000);
printf("sleep 1\n");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
编译程序: gcc main.c
按Ctrl+C(发送SIGINT信号), 程序输出received signal;
按Ctrl+Z(发送SIGSTOP信号), 程序被暂停并放到后台,但是没有死掉,还可以继续;
pgrep a.out
查看程序pid为32664;
kill -SIGCONT 32664
向程序发送继续运行的消息,程序会继续运行在后台;
jobs
查看后台运行的程序, a.out的job id为 1;
fg 1
将后台程序恢复到前台运行,此时再按Ctrl+C,程序仍输出received signal;
再按Ctrl+z
,程序暂停运行并放入后台。
bg 1
将后台暂停的程序继续运行。