linux下實現自動後台運行,脫離輸出到終端

來源:互聯網
上載者:User

看sipp的原始碼,看到裡面有實現完全後台運行,即脫離了終端。不向終端列印任何資訊。

代碼如下:

#include <unistd.h>#include <stdio.h>#include <errno.h>#include <fcntl.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <stdlib.h>#define BUFFER_SIZE 1024int main(int argc, char *argv[]){//return 0;        pid_t l_pid;        switch(l_pid = fork())        {            case -1:                // error when forking !                printf("Forking error");                exit(-1);            case 0:                // child process - poursuing the execution                // close all of our file descriptors                {                    int nullfd = open("/dev/null", O_RDWR);                    dup2(nullfd, fileno(stdin));                    dup2(nullfd, fileno(stdout));                    dup2(nullfd, fileno(stderr));                    //sleep(100);                    close(nullfd);                }                break;            default:                // parent process - killing the parent - the child get the parent pid                printf("Background mode - PID=[%d]\n", l_pid);                exit(1);        }                printf("Background mode - PID=[%d]\n", l_pid);                    sleep(100);}

關閉了stdin stdout stderr,而父進程在exit(1)處結束,而子進程繼續執行下面的sleep等代碼。

這裡

/dev/null是 

把/dev/null看作"黑洞".
它非常等價於一個唯寫檔案. 所有寫入它的內容都會永遠丟失. 而嘗試從它那兒讀取內容則什麼也讀不到. 然而, /dev/null對命令列和指令碼都非常的有用.

The function fileno() examines the  argument  stream  and  returns  its
       integer descriptor.

dup2 

 dup2() makes newfd be the copy of oldfd, closing newfd first if  neces‐
       sary, but note the following: 

If  oldfd  is  not a valid file descriptor, then the call fails, and
          newfd is not closed.

       *  If oldfd is a valid file descriptor, and newfd has the same value as
          oldfd, then dup2() does nothing, and returns newfd.

解釋下:fileno只是讀取FILE *或流的int標誌。

             dup2 原型是:int dup2(int oldfd, int newfd); 將newfd是oldfd的一個拷貝,如果newfd開啟,則先關閉它。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.