linux 重定向输出到文件、nohup、&

一、重定向输出到文件

重定向标准输出到指定文件
  1、覆盖 >

less /etc/passwd > test.txt
echo abc > test.txt

  2、追加 >>

echo 123 >> test.txt

 重定向标准错误到指定文件

  1、覆盖 2>

cd /eettcc/aabbcc 2> test.txt

  2、追加 2>>

cd /eettcc/aabbcc 2>> test.txt

这里的2是由shell修改的流ID,1是标准输出,2是标准错误输出。

 输出内容到文件f,错误信息输出到文件e:

ls /eettcc/aabbcc > f 2> e

标准输出和标准错误都输出到文件f:

ls /eettcc/aabbcc > f 2>&1   #错误信息覆盖
ls /eettcc/aabbcc > f 2>> f  #错误信息追加

二、nohup 和 & 的作用

1、& 后台运行程序,但日志打印到前台;可以重定向日志输出到指定目录,查看任务使用jobs
2、nohup, no hang up 不挂起。关闭终端窗口,程序不挂断。

(1) 示例程序 hello.c 如下:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
        fflush(stdout);
        setvbuf(stdout, NULL, _IONBF, 0);

        int i = 1;
        while (1) {
        printf("Hello, %d\n", i++);
        sleep(1);
    }
}

(2) 运行准备:yum install gcc  编译:gcc hello.c -o hello

(3) 运行程序 

命令 说明
./hello ctrl + c 以中断程序
   
./hello & ctrl + c 不能中断程序,因为程序在后台运行,只是日志打印到了前台
./hello >> hello.log & 重定向日志到 hello.log。可以使用 jobs 命令查看后台 hello 进程。 查看日志 tail -fn 5 hello.log
   
nohup ./hello ctrl + c 程序中断;关闭终端窗口,程序不中断
nohup ./hello & ctrl + c 不中断;关闭终端窗口,不中断

 

 

 


posted @ 2021-11-07 19:44  zhuangrunwei  阅读(2187)  评论(0编辑  收藏  举报