Use C to implement process monitoring. If a process exits, restart

Source: Internet
Author: User

# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <fcntl. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <Linux/types. h>
# Include <sys/Wait. H>
# Include <errno. h>
# Include <unistd. h>

// Programs to be monitored
# Define p1
"Hello1"
# Define p2
"Hello2"
# Define p3
"Hello3"
# Define path
"."

/*****************************/
Int is_run (char * Name );
Void killall_hello (void );
/*****************************/

// 1 is returned for running, 0 is returned for not running
Int is_run (char * name)
{
Int ret =-1;
Char Buf [256] = {'\ 0 '};
Snprintf (BUF, sizeof (BUF), "pidof % S>/dev/null", name );
Ret = System (BUF );
If (! Wexitstatus (RET) {// # include <sys/Wait. H>
// Printf ("% s is running! \ N ", name );
Return 1;
}
Else {
// Printf ("% s is not running! \ N ", name );

Return 0;
}
}
Void killall_hello (void)
{

Char Buf [128] = {'\ 0 '};
Snprintf (BUF, sizeof (BUF), "killall % s", P1 );
System (BUF );
Snprintf (BUF, sizeof (BUF), "killall % s", P2 );
System (BUF );
Snprintf (BUF, sizeof (BUF), "killall % s", P3 );
System (BUF );

}

Int main (INT argc, char ** argv)
{
Int p1_ret =-1;
Int p2_ret =-1;
Int p3_ret =-1;
Char Buf [128];
Bzero (BUF, sizeof (BUF ));

While (1 ){

P1_ret = is_run (P1 );
P2_ret = is_run (P2 );
P3_ret = is_run (P3 );

If (! (P1_ret & p2_ret & p3_ret ))
{
Killall_hello ();
Printf ("Rerun hello3 \ n ");
Snprintf (BUF, sizeof (BUF), "% S/% S &", path, P3 );
System (BUF );

// Print log information
System ("date> W. log ");
If (! P1_ret ){
Snprintf (BUF, sizeof (BUF), "Echo % s not run, killall, run % S> W. log", P1, P3 );
System (BUF );
}
Else if (! P2_ret ){
Snprintf (BUF, sizeof (BUF), "Echo % s not run, killall, run % S> W. log", P2, P3 );
System (BUF );
}
Else if (! P3_ret ){
Snprintf (BUF, sizeof (BUF), "Echo % s not run, killall, run % S> W. log", P3, P3 );
System (BUF );
}
}
Sleep (5 );
}
Exit (0 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.