Chinaunix首页 | 论坛 | 博客
  • 博客访问: 627043
  • 博文数量: 121
  • 博客积分: 8469
  • 博客等级: 中将
  • 技术积分: 1065
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-03 10:32
文章分类

全部博文(121)

文章存档

2013年(1)

2012年(15)

2010年(2)

2009年(8)

2008年(95)

我的朋友

分类: LINUX

2008-07-11 10:14:19

在一个项目中需要编程控制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);
}
阅读(1503) | 评论(0) | 转发(0) |
0

上一篇:__setup宏简介

下一篇:我的fstab

给主人留下些什么吧!~~