2

I have a program that creates a fork that uses execve to run a program that have a SegFault and exit after catching the signal. In my signal handler, I should obtain "Segmentation fault (Core dumped)" but nothing is written. So I'm asking : how to handle a segfault signal in a child process ? My code is the following :

int     child_management(char **env, char **arguments)
{
  char  **paths;
  char  *current_path;
  char  *target_path;
  int   found;
  int   i;

  i = -1;
  found = 0;
  paths = get_paths(env);
  if (execve(arguments[0], arguments, env) == -1)
    {
      while (paths[++i] != NULL)
        {
          current_path = my_strcat(paths[i], "/");
          target_path = my_strcat(current_path, arguments[0]);
          found = (execve(target_path, arguments, env) == -1 && found == 0) ? 0 : 1;
          free(current_path);
          free(target_path);
        }
      if (!found && !is_existing_builtin(arguments[0]))
        my_printf("%s: Command not found.\n", arguments[0]);
    }
  free(arguments);
  free(paths);
  if (signal(SIGSEGV, segf_handler) == SIG_ERR);
  exit(0);
}

void    segf_handler()
{
  my_printf("Segmentation fault (Core dumped)\n");
}

int     execute_program(char *str, char **av, char **env)
{
  pid_t pid;
  char  **arguments;

  pid = fork();
  arguments = my_str_explode(str, ' ');
  if (pid > 0)
    {
      parent_management(pid, arguments, env);
    }
  else if (pid == 0)
    {
      child_management(env, arguments);
    }
}

Please notice that I am doing an exercice and I'm not allowed to use another function than signal so don't tell me about sigaction

Orionss
  • 725
  • 2
  • 10
  • 26

1 Answers1

3

You can't catch the SEGV signal inside the child because calling execve replaces the code running in the child with that program.

You can however catch the CHLD signal in the parent when the child process dies. You'll need to examine the status returned from wait() to see how/why it died though.

Chris Turner
  • 8,082
  • 1
  • 14
  • 18
  • This solved my problem because it caused me to ask someone to know if I could use the macros and I could ! Thanks ! – Orionss Jan 18 '17 at 17:49