[英]Job control in linux with C
我知道的:
当一个进程正在运行时,我可以按Ctrl + Z并暂停它。 with bg
和fg
命令我可以在“后台”或“前台”模式下运行它。
我在问什么:
有没有办法暂停进程,将其发送到 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 自己接受输入,并与子进程并行运行。
你不能。 bg
和fg
是 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.