嵌入式设备中实现ping功能代码

Vfork出一个子进程,然后监控。


int NetPing(char *server_ip)
{
	pid_t pid;
	int i = 0;
	int stat;
	const int loopCnt = 3; //ping 3 times

	while(i < loopCnt)
	{
		if((pid = vfork()) < 0)
		{
			RPT(RPT_ERR, "vfork error!");
			return -1;
		}
		else if(pid == 0)
		{
			if( execlp("ping", "ping", "-c", "1","-W", "3", server_ip, (char *)0) < 0)
			{
				RPT(RPT_ERR, "execlp 'ping -c 1 %s' error!", server_ip);
				return -1;
			}
		}

		waitpid(pid , &stat, WUNTRACED);
        if (stat == 0)
        {
            RPT(RPT_INF, "ping successful pid=%d", pid);
            return 0;
        }
		else
		{
			RPT(RPT_ERR, "ping error!, can not connect to %s", server_ip);
		}
		
        mssleep(50);
        i++;
	}

	return -1;
}


关键点:

嵌入式设备中实现ping功能代码_第1张图片

你可能感兴趣的:(C语言)