c - 如果 exec 失败,则终止子进程

标签 c unix exec kill

我正在创建一个程序,该程序从一个 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/

相关文章:

C 程序值从 1 个字符变为 2 个字符

Windows 等效于 'nice'

linux - 如何将本地 shell 变量导出到多命令 ssh 中?

java - 使用超时处理程序从 PHP 调用 Java

unix - 重定向在 UNIX 内部如何工作

php - Kohana - 发布带有 ".exec"正则表达式的 javascript 代码返回内部错误

c - C 中的 ADT 定义函数

字符数组和指针

PHP passthru() 返回 "sh: 1: svn: not found "错误

c - window C : TCP Socket send&recv at the same time