Search code examples
cpinglcd

If then statement c programming


I was wondering if someone could help me write an if then statement for a ping..

Example IP: 192.168.10.1

Here's what I have so far..

lcd_command(LINE_1);
if system(("ping -c1 192.168.10.1")) {
lcd_writechars("Ping Successful");
}
else {
lcd_writechars("Ping Successful");
}

Basically, I want the script to ping every 10 seconds and have "Ping Successful" be displayed, on my LCD, when the host is reachable. When the host is unreachable, I want "Ping Unsuccessful" to be displayed, on my LCD, until the host is reachable again.

If someone could help me out, I would greatly appreciate it!


Solution

  • Your braces are not syntactically correct (Bracket need to start after if and not after system). Also please find below the proper usage of return status of system call using the W* macros.

    int status = system("ping -c1 192.168.10.1");
    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
    lcd_writechars("Ping Successful\n");
    }
    else {
    lcd_writechars("Ping failed\n");
    }