【问题标题】:Spawn an independent child产生一个独立的孩子
【发布时间】:2011-08-25 21:07:58
【问题描述】:

如何使用 C 来生成一个独立的子进程,它可以在不考虑父进程的情况下执行其业务?

我想生成几个进程,在它们创建后不久,它们会在完成工作前进入睡眠状态大约 2 分钟。

但是,我不希望父亲等到孩子完成,因为与此同时我想产生更多的进程。

我在 Linux 上。

【问题讨论】:

  • 刚才看到没提。让我编辑我的问题。我要的是进程。

标签: c linux process spawn


【解决方案1】:

使用 fork()。 The fork() System Call

pid_t pid = fork (); 
if (pid < 0) 
  // Error
else if (pid == 0) 
  // Child Process
  // Sleep 2 min. ?!
else 
  // Code for Father

【讨论】:

  • OP 明确表示父进程不应等待。因此,使用wait(2) 与问题无关。
【解决方案2】:

只需使用fork(2) 生成所需数量的进程,然后在父进程中调用exit()。孤儿将被init流程收养。

【讨论】:

    【解决方案3】:

    如果您想要创建多个子进程在创建后立即执行“自己的业务”,则应使用vfork()(用于创建新进程而无需完全复制父进程的地址空间)和exec()家庭用你想要的任何东西替换子进程的图像。

    如果您不希望父亲等到孩子完成后,您应该利用异步信号处理。当子进程结束时发送 SIGCHLD。因此,您可以将wait() 放在 SIGCHLD 而不是父进程的信号处理程序中,并让信号处理程序收集子进程的返回状态。

    下面是一个玩具示例:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <signal.h>
    #include <stdlib.h>
    
    sig_atomic_t child_process_ret_status;
    
    void spawn(char *program,char *argv[]){
        pid_t child_pid=vfork();
    
        if(child_pid>0){
            printf("the parent process pid: %d\n",(int)getpid());
            printf("the cpid: %d\n",(int)child_pid);
            system("ping -c 10 www.google.com");
        }else{
            printf("the new process %d is going to execute the new program %s\n",(int)getpid(),program);
            execvp(program,argv);
            printf("you'll never see this if everything goes well.\n");
        }
    }
    
    
    void child_process_ret_handle(int sigval){
        if(sigval == SIGCHLD){
            printf("SIGCHLD received !\n");
            wait(&child_process_ret_status);
        }
    }
    
    int main(void){
        signal(SIGCHLD,child_process_ret_handle);
        char *program="sleep";
        char *argv[]={
            "sleep",
            "5",
            NULL
        };
    
        spawn(program,argv);
        if(WIFEXITED (child_process_ret_status)){
            printf("child process exited successfully with %d\n",WEXITSTATUS (child_process_ret_status));
        }else{
            printf("the child process exited abnormally\n");    
        }
    
        printf("parent process: %d returned!\n",getpid());
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      相关资源
      最近更新 更多