簡體   English   中英

linux 和 C 中的作業控制

[英]Job control in linux with C

我知道的:

當一個進程正在運行時,我可以按Ctrl + Z並暫停它。 with bgfg命令我可以在“后台”或“前台”模式下運行它。

我在問什么:

有沒有辦法暫停進程,將其發送到 C 的后台或前台運行?

編輯:我有進程ID。 例如,我想將該過程發送到后台。

You can suspend it with kill(pid, SIGSTOP) , but making it foreground or background is a function of the shell that ran it, since what it actually affects is whether the shell displays a prompt (and accepts a new command) immediately or waits直到作業退出。 除非 shell 提供 RPC 接口(如 DBus),否則沒有干凈的方法來更改等待/不等待標志。

Linux 進程通常可以通過向其發送 SIGSTOP 信號來暫停或通過向其發送 SIGCONT 信號來恢復。 在 C 中,

#include <signal.h>

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

進程可以使用pause()暫停自己。

“前景”和“背景”模式不是進程的屬性。 它們是父 shell 進程如何與它們交互的屬性:在 fg 模式下,對 shell 的輸入傳遞給子進程,而 Z2591C98B70119FE624898B1E424B59 的子進程退出。 在 bg 模式下,shell 自己接受輸入,並與子進程並行運行。

你不能。 bgfg是 shell 命令,您不能在 C 的任意 shell 中調用命令。

通常的方法是分叉一個子進程,然后退出父進程。 看這個簡單的例子

#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;  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM