|
我想写一个像telnetd一样的服务程序,加到xinetd中运行,
首先写了一个脚本如下:
===============================================service appdsvr
{
disable = no
flags = REUSE
socket_type = stream
protocol = tcp
user = root
wait = no
port = 1011
server = /home/workroom/appdsvr/debug/src/appdsvr
}
===============================================同时也把端口加到/etc/service中
然后写了server代码,如下:
===============================================struct sockaddr_in sin;
int sock_descriptor;
int temp_sock_descriptor;
int address_size;
int on = 1;
string strrecv;
struct servent *sp;
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
sp = getservbyname("appdsvr", "tcp");
sin.sin_port = sp->s_port;
sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if(sock_descriptor < 0)
{
msgout(3,"Create socket failed.");
exit(1);
}
(void) setsockopt(sock_descriptor, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(bind(sock_descriptor, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
msgout(3,"Bind failed. %s", strerror(errno));
close(sock_descriptor);
exit(1);
}
if(listen(sock_descriptor, 1) < 0)
{
msgout(3,"Listen failed.");
close(sock_descriptor);
exit(1);
}
if(-1 == (temp_sock_descriptor = accept(sock_descriptor, (struct sockaddr *)&pin, (socklen_t *)&address_size)))
{
msgout(3,"Accept failed.");
close(sock_descriptor);
exit(1);
}
......
===============================================
根据调试,发现当程序作为daemon运行后,在bind的时候会发生“Address already in use”的错误。
但是如果不运行为daemon,而将dsvr单独运行没有问题。
不知道哪位有这方面的经验,解我疑惑,不胜感激。 |
|