#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
/*
*****************************************************************************************
* 函 数 名: run_ping
* 功能说明: 运行ping命令,并判断是否成功
* 形 参:无
* 返 回 值: 0:ping成功
* -1:失败
*****************************************************************************************
*/
int run_ping(char *_pIpAddr) {
int cnt = 0;
int result = 0;
pid_t pid;
if ((pid = vfork()) < 0) {
printf("%s: vfork error: %s\n", __FUNCTION__, strerror(errno));
return -1;
} else if (pid == 0) { //子进程
if (execlp("ping", "ping","-c","1", _pIpAddr, (char*)0) < 0) {
printf("%s: execlp error: %s\n", __FUNCTION__, strerror(errno));
return -1;
}
}
waitpid(pid, &result, 0);
if (WIFEXITED(result)) {
if (WEXITSTATUS(result) != 0) {
printf("%s: execute command: %s failed(%d)\n", __FUNCTION__, "ping", WEXITSTATUS(result));
result = -1;
} else {
result = 0;
}
} else {
result = 0;
}
if (result) {
printf("ping %s error!\n", _pIpAddr);
return -1;
} else {
printf("ping %s ok!\n", _pIpAddr);
return 0;
}
}
#define TEST_IP "183.2.172.185"
#define ERROR_IP "192.168.100.100"
int main(void){
run_ping(TEST_IP);
run_ping(ERROR_IP);
}
0 条评论