如果exec失败,则杀死子进程

时间:2014-10-02 08:41:44

标签: c unix exec kill

我正在创建一个程序,可以从一个父级创建许多子级。 如果执行exec时出错,我不希望创建更多子项。 即使在exec失败后,以下代码仍会继续创建子代。

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);
        }


    }


}

感谢 丹尼尔

1 个答案:

答案 0 :(得分:3)

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

相关问题