2010-06-04 142 views
0

我正在學習如何在Linux操作系統平臺上編程,以及在後臺進程中如何運行我的應用程序。如何在後臺進程中運行linux應用程序?

就像在這種情況下的例子:當在shell中執行我的應用程序時,它會自動運行在後臺進程中。請注意,當我運行我的應用程序時,我不需要shell中的「&」。什麼標準的Linux功能來做這個實現?

我該如何殺死或終止在代碼中後臺運行的應用程序?我的意思是我不需要執行kill shell命令來在後臺終止我的應用程序?或者,如果應用程序符合條件,則會自行終止或自行終止。

非常感謝。

回答

4

你想守護你的程序。這通常由fork()和一些其他系統調用完成。

還有更多的細節here

後臺應用程序可以通過使用kill被殺死。守護進程將其進程ID(PID)寫入一個衆所周知的文件中以便輕鬆定位是一種很好的做法。

+0

什麼,你的意思是我必須保存在一個文件中的應用程序的PID值,這樣,如果我要終止的應用程序,我剛纔讀的價值和使用在同一代碼文件中使用kill shell命令殺死應用程序的值? – domlao 2010-06-04 01:57:44

+0

@sasayins:如果你正在從另一個程序(不是腳本)中殺死進程,應該使用'kill(2)'函數。如果你想殺死父進程的子進程,不需要PID文件,因爲fork將PID返回給父進程。 – 2010-06-04 02:07:55

1

fork(2)給你一個新的過程。在孩子中,您運行exec(3)函數之一來替換它爲新的可執行文件。父母可以使用wait(2)函數之一等待孩子終止。 kill(2)可用於發送信號到另一個進程。

2

雖然你應該瞭解fork()exec()wait()kill(),它有時會更方便,只需使用daemon(3)如果它存在。

注意事項:

  • 不在POSIX.1-2001
  • 並非存在於所有的BSD的(可能被命名爲別的東西,不過)

如果可移植性不是主要問題,這很方便。如果可移植性是一個主要問題,您可以隨時編寫自己的實現並使用它。

從手冊頁:

SYNOPSIS 
     #include <unistd.h> 

     int daemon(int nochdir, int noclose); 

DESCRIPTION 
     The daemon() function is for programs wishing to detach themselves from the 
     controlling terminal and run in the background as system daemons. 

     If nochdir is zero, daemon() changes the calling process's current working directory 
     to the root directory ("/"); otherwise, the current working directory is left 
     unchanged. 

     If noclose is zero, daemon() redirects standard input, standard output and standard 
     error to /dev/null; otherwise, no changes are made to these file descriptors.