使用C将exec进程发送到后台? [英] Using C to send an exec process to the background?

查看:125
本文介绍了使用C将exec进程发送到后台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question sounds the same as this but it isn't:

在Linux中使用C

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

I know how to do fork() but not how to send a process to the background. My program should work like a simple command unix shell that supports pipes and background processes. I could do pipe and fork but I don't know how to send a process to the background with & like the last line of the program:

~>./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");
    }
}

简单的英语解决方案似乎在这里: 如何在C的背景?

The solution in plain English appears to be here: How do I exec() a process in the background in C?

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

Catch SIGCHLD and in the the handler, call wait().

我在正确的轨道上吗?

推荐答案

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

Q: How do I send a process to the background?

A:通常,您正在做的事情就是:fork()/exec().

A: In general, exactly what you're already doing: fork()/exec().

问:什么不如您预期的那样?

Q: What's not working as you expect?

我怀疑您可能还想要"nohup"(将孩子与父母完全分离).

I suspect maybe you also want a "nohup" (to completely disassociate the child from the parent).

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

The key to doing this is to run "setsid()" in the child process:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆