|
发表于 2003-2-26 17:51:27
|
显示全部楼层
我觉得通过管道应该有办法实现。
但并不确定,尤其不确定是否是更好的办法。
我给个例子你看一下,就是那个防idle的BBS程序。
因为我现在没有时间写程序来测试,所以你先试试,
等我忙完手头上的东西,就来写个程序看看。
- #include <unistd.h>
- #include <signal.h>
- #include <fcntl.h>
- #include <termios.h>
- #include <sys/time.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdio.h>
- struct termios tsave;
- void
- scan_mode (void)
- {
- struct termios tbuf;
- if (!isatty (0))
- exit (1);
- if (tcgetattr (0, &tbuf) == -1)
- exit (1);
- tsave = tbuf;
- tbuf.c_lflag &= ~(ECHO | ICANON | ISIG);
- tbuf.c_cc[VMIN] = tbuf.c_cc[VTIME] = 0;
- if (tcsetattr (0, TCSANOW, &tbuf) == -1)
- exit (1);
- }
- void
- restore_mode (int i)
- {
- tcsetattr (0, TCSANOW, &tsave);
- exit (1);
- }
- main (int argc, char **argv)
- {
- int fdin[2], fdout[2];
- int fdw, fdr, i;
- int j;
- fd_set rdfds;
- struct timeval timeout;
- char bufer[1024], ch = 12;
- if (pipe (fdin) == -1)
- exit (1);
- if (pipe (fdout) == -1)
- exit (1);
- switch (fork ())
- {
- case -1:
- exit (1);
- case 0:
- //printf("son\n");
- close (0);
- dup (fdin[0]);
- close (fdin[0]);
- close (fdin[1]);
- close (1);
- dup (fdout[1]);
- close (fdout[0]);
- close (fdout[1]);
- execl ("/usr/bin/telnet", "telnet", "202.120.225.9", 0);
- //这里你可以把202.112.58.200换成别的bbs地址.
- printf ("failed %s", argv[1]);
- exit (1);
- default:
- //printf("parent");
- close (fdin[0]);
- fdw = fdin[1];
- close (fdout[1]);
- fdr = fdout[0];
- }
- scan_mode ();
- (void) signal (SIGPIPE, restore_mode);
- fcntl (0, F_SETFL, O_NONBLOCK);
- fcntl (fdr, F_SETFL, O_NONBLOCK);
- timeout.tv_sec = 600;
- timeout.tv_usec = 0;
- while (1)
- {
- FD_ZERO (&rdfds);
- FD_SET (0, &rdfds);
- FD_SET (fdr, &rdfds);
- if (select (fdr + 1, &rdfds, NULL, NULL, &timeout))
- {
- i = read (0, bufer, 1024);
- if (i > 0)
- {
- timeout.tv_sec = 600;
- timeout.tv_usec = 0;
- write (fdw, bufer, i);
- }
- i = read (fdr, bufer, 1024);
- if (i > 0)
- {
- write (1, bufer, i);
- }
- }
- else
- {
- timeout.tv_sec = 600;
- timeout.tv_usec = 0;
- write (fdw, &ch, 1);
- }
- }
- }
- //end
复制代码 |
|