开发者

Spawn an independent child

How can you use C to spawn an independent child process that goes about its business without thinking about the father?

I want to spawn several processes and shortly after they have been created they go to sleep for about 2 minutes before they do their job.

开发者_如何学运维

However, I don't want the father to wait until the child is finished because in the meantime I want to spawn off more processes.

I'm on Linux.


Use 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


Simply spawn as many processes as you need using fork(2), then call exit() in the parent process. The orphaned children will be adopted by the init process.


If what you want is creating multiple child processes doing their "own business" right after their creation, you should use vfork() (used to create new processes without fully copying the address space of the father process) and exec() family to replace the children processes' images with whatever you want.

if you don't want the father to wait until the child is finished, you should take advantage of asynchronous signal handling. A SIGCHLD is sent when a child process ends. So you can put the wait() within the signal handler for SIGCHLD rather than the father process and let the signal handler collect returning status for child process.

Below is a toy example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜