我正在创建一个程序,该程序从一个 parent 那里创造出许多 child 。
如果执行 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);
}
}
}
谢谢 丹尼尔
最佳答案
需要在kill()
后面加上return语句,否则子进程执行完kill()
后会再次循环,成为父进程。
关于c - 如果 exec 失败,则终止子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26157220/