Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Better way to monitor and kill other program's stalled process in linux?

I need my program to run some other program, but if the other program won't return within some time limit, I need to kill it. I came up with the following solution that seems to be working.

int main()
{
int retval, timeout=10;
pid_t proc1=fork();

if(proc1>0)
{
    while(timeout)
    {
        waitpid(proc1, &retval, WNOHANG);
        if(WIFEXITED(retval)) break; //normal termination
        sleep(1);
        --timeout;
        if(timeout==0)
        {
            printf("attempt to kill process\n");
            kill(proc1, SIGTERM);
            break;
        }
    }
}
else if(proc1==0)
{
    execlp("./someprogram", "./someprogram", "-a", "-b", NULL);
}
//else if fork failed etc.
return 0;
}

I need my program to be as robust as possible but I am new to programming under linux so I may not be aware of possible problems with it. My questions are: 1. Is this a proper solution to this particular problem or are there better methods? 2. Does anyone see possible problems or bugs that can lead to an unexpected behavior or a leak of system resources?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

(WIFEXITED(retval)) won't return true if the program is killed by a signal (including say a crash due to segmentation violation).

Probably best to just check for a successful return from waitpid. That will only happen if the program is terminated (whether voluntarily or not).

Depending on how important it is to make sure the process is gone...
After killing the process with SIGTERM, you could sleep another second or so and if it's still not gone, use SIGKILL to be sure.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda