代碼在 MAC OS 下運行良好,在 Linux 下得話需要稍作修改
#include?<stdio.h>#include?<fcntl.h>
#include?<string.h>
#include?<stdlib.h>
#include?<unistd.h>
int?main(void)
{
char?host[256],?cmd[256];
printf("please?input?dest_host:");
scanf("%s",?host);
strncpy(cmd,?"ping?-c5?",?9);
strncat(cmd,?host,?strlen(host));
strncat(cmd,?"?>?ping.txt",?11);
pid_t?pid?=?fork();
if(pid?<?0)
{
printf("fork?error\n");
exit(-1);
}
if(pid==0)
{
if(execlp("/bin/sh",?"sh",?"-c",?cmd,?(char?*)0)?<?0)
printf("execlp?error\n");
exit(0);
}
if(waitpid(pid,?NULL,?0)?<?0)
printf("waitpid?error\n");
int?fd?=?open("ping.txt",?O_RDWR);
int?n;
char?buf[1024];
n?=?read(fd,?buf,?sizeof(buf));
if(n?<=?0)
{
printf("read?error\n");
exit(-1);
}
if(strstr(buf,?"100.0%")?==?NULL)
printf("can?reach?%s",?host);
else
printf("can't?reach?%s",?host);
close(fd);
return?0;
}
如果妳想要 ping 程序,剛好我最近寫了壹個,要的話私信