看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開啟,則先關閉它。