2011-07-04 41 views
4

我知道什麼:作業控制在Linux中使用C

當一個進程正在運行,我可以按「Ctrl + Z」,並暫停了。與bgfg命令我可以運行它在「後臺」或「前景」模式。

什麼我aksing:

有沒有辦法進程暫停,將其發送到用C背景或前景運行?

編輯: 我有進程ID。例如,我想將該進程發送到後臺。

+0

可能發送了SIGSTP信號,但是我不知道你是否可以程序化的方式恢復它作爲bg或fg進程相對於運行該進程的shell(我認爲你可以,但我可能是錯誤的)。你可以嘗試使用'system',但我不確定像'system(「bg 1」)'這樣的東西是可行的,因爲作業對運行中的shell是「本地」的,而afaik系統可以執行它自己的「shell解釋器」實例,或者無論如何 – ShinTakezou

回答

5

您可以使用kill(pid, SIGSTOP)掛起它,但使其前景或後臺是運行它的shell的函數,因爲它實際影響的是shell是否立即顯示提示(並接受新命令)或等待直到工作退出。除非shell提供RPC接口(如DBus),否則沒有乾淨的方法來更改等待/不等待標誌。

+0

你總是可以使用gdb/ptrace作爲RPC ... – geocar

+0

@geocar:在shell的內存空間中查找標誌,然後通過調試API進行更改,並不符合「** clean **方法」 IMO。 –

1

你不能。 bgfg是shell命令,並且不能從C的任意shell中調用命令。

1

通常的方法是分離子進程並退出父進程。 See this for a simple example

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 

#define EXIT_SUCCESS 0 
#define EXIT_FAILURE 1 

static void daemonize(void) 
{ 
    pid_t pid, sid; 

    /* already a daemon */ 
    if (getppid() == 1) return; 

    /* Fork off the parent process */ 
    pid = fork(); 
    if (pid < 0) 
    { 
     exit(EXIT_FAILURE); 
    } 
    /* If we got a good PID, then we can exit the parent process. */ 
    if (pid > 0) 
    { 
     exit(EXIT_SUCCESS); 
    } 

    /* At this point we are executing as the child process */ 

    /* Change the file mode mask */ 
    umask(0); 

    /* Create a new SID for the child process */ 
    sid = setsid(); 
    if (sid < 0) 
    { 
     exit(EXIT_FAILURE); 
    } 


    /* Change the current working directory. This prevents the current 
     directory from being locked; hence not being able to remove it. */ 
    if ((chdir("/")) < 0) 
    { 
     exit(EXIT_FAILURE); 
    } 

    /* Redirect standard files to /dev/null */ 
    freopen("/dev/null", "r", stdin); 
    freopen("/dev/null", "w", stdout); 
    freopen("/dev/null", "w", stderr); 
} 

int main(int argc, char *argv[]) 
{ 
    daemonize(); 

    /* Now we are a daemon -- do the work for which we were paid */ 

    return 0; 
} 
2

一個Linux過程通常可以通過發送它的SIGSTOP信號或恢復通過發送它SIGCONT信號被暫停。在C中,

#include <signal.h> 

kill(pid, SIGSTOP); 
kill(pid, SIGCONT); 

進程可以使用pause()掛起自己。

「前景」和「背景」模式不是過程的屬性。它們是父shell進程如何與它們交互的屬性:在fg模式下,shell的輸入被傳遞給子進程,並且shell等待子進程退出。在bg模式下,shell自己接受輸入,並且與子進程並行運行。

+0

感謝'#包括',沒有人在任何地方。 –