1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

C Program to check if unix service is up/down

Discussion in 'C' started by nrhayyal, Jan 21, 2013.

  1. nrhayyal

    nrhayyal New Member

    Joined:
    Dec 24, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi All,
    Is there any API in C to check if any of the unix service is up or down.
    Like i want to know if syslog service is up and down in C program.
    if down how to bring it up using C program?
    please help...

    Regards
    nrhayyal
     
  2. DRK

    DRK New Member

    Joined:
    Apr 13, 2012
    Messages:
    44
    Likes Received:
    3
    Trophy Points:
    0
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    #define PROCESS_NAME "syslog"
    #define TEMP_FILE_NAME "temp.txt"
    #define MAX_LINE_LENGTH 100
     
    int main()
    {
        FILE *temp;
        char line[MAX_LINE_LENGTH];
        int found = 0;
     
        if (system("ps > "TEMP_FILE_NAME) == 0)
        {
            temp = fopen(TEMP_FILE_NAME, "r");
            if (temp != NULL)
            {
                while (fgets(line, MAX_LINE_LENGTH, temp) != NULL)
                {
                    if (strstr(line, PROCESS_NAME) != NULL)
                    {
                        found = 1;
                        break;
                    }
                }
                fclose(temp);
                if (found == 1)
                {
                    puts(PROCESS_NAME" is running");
                }
                else
                {
                    puts(PROCESS_NAME" is not running");
                }
            }
            else
            {
                puts("Unable to open temporary file "TEMP_FILE_NAME);
            }
        }
        else
        {
            puts("Unable to get process list");
        }
        system("rm "TEMP_FILE_NAME);
     
        return 0;
    }
    
     
    shabbir likes this.

Share This Page