简体   繁体   中英

kill child process if exec fails

I am creating a program that creates many children from one parent. I do not want any more children to be created, if there was an error executing exec . The following code still continues to create children even after an exec failure.

void synch_signal (int sig)
{
  fprintf(stderr,"%s","ERROR");
  exit(0);
}


void create_children(int numberOfChildren, char **argc){
    struct sigaction usr_action;

    usr_action.sa_handler = synch_signal;
    sigaction (SIGUSR1, &usr_action, NULL);

    int pid = 0;
    char mystring[100] = { 0 };

    for (i; i <numberOfChildren; i++){


        //removed for simplicity. 

        pid = fork();

        if (pid){       
            //removed       
        }
        else {
             //removed 
             exec(...);
             //exec failed
             kill (getppid (), SIGUSR1);
        }


    }


}

thanks daniel

您需要在kill()之后添加return语句,否则子进程将在kill()函数完成后再次循环,并成为父进程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM