Linux C 调用 ping命令 检测网络状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int ping_status( char *ip)
{
     int i, status;
     pid_t pid;
     printf( ">>>>>>>>>>>>> ping_status\n " );
     // 不同则循环检测多次
     for (i = 0; i < 3; ++i)
     {
         // 新建一个进程来执行ping命令
         if ((pid = vfork()) < 0)
         {
             printf( "vfork error" );
             continue ;
         }
 
         if (pid == 0)
         {
             // 执行ping命令
             //if (execlp("ping", "ping", "-c 1", ip, (char*)0) < 0)
             //if ( execlp("ping", "ping","-c 1",svrip, (char*)0) < 0)
             if ( execlp( "ping" , "ping" , "-c" , "1" ,ip, ( char *)0) < 0)
             {
                 printf( "execlp error\n" );
                 exit(1);
             }
         }
 
         waitpid(pid, &status, 0);
 
         // 相等说明正常
         if (status == 0)
             return 0;
 
       //  sleep(2);
     }
 
     return -1;
}
Logo

更多推荐