在一个项目中需要编程控制ADSL Modem,读取测试数据,以下就是相关的代码:
#include
#include
#include
#include
int sendcmd(int fo, int fi, const char *cmd, char *buf, size_t size)
{
int n=0;
struct pollfd fds[1];
fds[0].fd=fi;
fds[0].events=POLLRDNORM;
fds[0].revents=0;
write(fo, cmd, strlen(cmd)); /* send command */
while(poll(fds, 1, 100)>0)
n+=read(fi, &buf[n], size);
buf[n]=0;
printf("%s", buf);
fflush(stdout);
return(0);
}
init_telnet(const char *ip, const char *user, const char *passwd)
{
int fd1[2], fd2[2];
pid_t pid;
char buf[1024];
if (pipe(fd1)<0 || pipe(fd2)<0)
return(-1);
if ((pid=fork())<0)
return(-2);
if (!pid)
{ /* child */
close(fd1[1]);
close(fd2[0]);
dup2(fd1[0], STDIN_FILENO); /* join child's stdin to parent's fd1[1] */
dup2(fd2[1], STDOUT_FILENO); /* join child's stdin to parent's fd2[0] */
close(STDERR_FILENO); /* discard child's stderr */
close(fd1[0]);
close(fd2[1]);
if (execl("/usr/bin/telnet", "telnet", ip, NULL)<0)
perror(NULL);
exit(0);
}
close(fd1[0]);
close(fd2[1]);
if ((user!=NULL) && (passwd!=NULL))
{
sendcmd(fd1[1], fd2[0], user, tp_buf, sizeof(tp_buf));
sendcmd(fd1[1], fd2[0], passwd, tp_buf, sizeof(tp_buf));
}
else if ((user==NULL) && (passwd!=NULL))
{
sendcmd(fd1[1], fd2[0], passwd, tp_buf, sizeof(tp_buf));
}
close(fd1[1]);
close(fd2[0]);
return(0);
}
阅读(1537) | 评论(0) | 转发(0) |