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 不中斷;關閉終端窗口,不中斷

 

 

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM