使用C将exec进程发送到后台?

时间:2012-06-11 18:27:00

标签: c unix process exec fork

我的问题听起来与此相同,但事实并非如此:

Start a process in the background in Linux with C

我知道如何做fork()但不知道如何将进程发送到后台。我的程序应该像一个支持管道和后台进程的简单命令unix shell。我可以做管道和分叉,但我不知道如何使用&将进程发送到后台,就像程序的最后一行一样:

~>./a.out uname
SunOS
^C
my:~>./a.out uname &

如何实现后台流程?

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

#define TIMEOUT (20)

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

  if(argc > 1 && strncmp(argv[1], "-help", strlen(argv[1])) == 0)
    {
      fprintf(stderr, "Usage: Prog [CommandLineArgs]\n\nRunSafe takes as arguments:\nthe program to be run (Prog) and its command line arguments (CommandLineArgs) (if any)\n\nRunSafe will execute Prog with its command line arguments and\nterminate it and any remaining childprocesses after %d seconds\n", TIMEOUT);
      exit(0);
    }

  if((pid = fork()) == 0)        /* Fork off child */
    {
      execvp(argv[1], argv+1);
      fprintf(stderr,"Failed to execute: %s\n",argv[1]);
      perror("Reason");
      kill(getppid(),SIGKILL);   /* kill waiting parent */
      exit(errno);               /* execvp failed, no child - exit immediately */
    }
  else if(pid != -1)
    {
      sleep(TIMEOUT);
      if(kill(0,0) == 0)         /* are there processes left? */
    {
      fprintf(stderr,"\Attempting to kill remaining (child) processes\n");
      kill(0, SIGKILL);      /* send SIGKILL to all child processes */
    }
    }
  else
    {
      fprintf(stderr,"Failed to fork off child process\n");
      perror("Reason");
    }
}

普通英语的解决方案似乎在这里: How do I exec() a process in the background in C?

  

捕获SIGCHLD并在处理程序中调用wait()。

我是在正确的轨道上吗?

1 个答案:

答案 0 :(得分:4)

  

问:如何将流程发送到后台?

答:一般来说,正是你正在做的事情:fork()/ exec()。

问:什么不能按预期工作?

我怀疑也许你也想要一个“nohup”(让孩子完全与父母分离)。

执行此操作的关键是在子进程中运行“setsid()”: