Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!