Linux下编的TCP服务器,"close"在此作用域中尚未声明?

adamwyb 2011-06-01 09:03:28
Linux下编的TCP服务器,最后调用close关掉监听socket和连接socket,但是用g++编译后,提示错误:"close"在此作用域中尚未声明。如果把close注释掉,就能编译通过,而且运行正常,这是什么原因?谢谢!
...全文
1339 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
facingwaller 2013-01-12
  • 打赏
  • 举报
回复
添加头文件#include <unistd.h> 是正解
zhuzhu510 2012-09-10
  • 打赏
  • 举报
回复
添加头文件#include <unistd.h>
blueboy82006 2012-08-06
  • 打赏
  • 举报
回复
刚也遇到了这个问题,不知道是不是系统环境的影响,有什么好的解决办法?
bluesky12312388 2011-06-02
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 adamwyb 的回复:]

引用 7 楼 luciferisnotsatan 的回复:
打开<sys/socket.h>,看看里面有些什么


看了,里面确实没有close,只有shutdown,但是这个文件我没有动过,为什么没有close?
[/Quote]
本来就没有。

你自己先man socket 看后面相关函数明显没有close,只有shutdown(2);

man P 2 shutdown

#include <sys/socket.h>

原型
int shutdown(int sockfd,int how);


adamwyb 2011-06-02
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 luciferisnotsatan 的回复:]
打开<sys/socket.h>,看看里面有些什么
[/Quote]

看了,里面确实没有close,只有shutdown,但是这个文件我没有动过,为什么没有close?
luciferisnotsatan 2011-06-02
  • 打赏
  • 举报
回复
打开<sys/socket.h>,看看里面有些什么
wesleyluo 2011-06-02
  • 打赏
  • 举报
回复
把生成的中间文件清理下,重新编译看看。
adamwyb 2011-06-02
  • 打赏
  • 举报
回复
代码如下:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

using namespace std;

int main(int argc, char* argv[])
{
printf("start!\n");

int socketListen = socket(AF_INET, SOCK_STREAM, 0);

sockaddr_in addrSvr;
addrSvr.sin_family = AF_INET;
addrSvr.sin_addr.s_addr = htonl(INADDR_ANY);
addrSvr.sin_port = htons(9000);

printf("bind...\n");
if(-1 == bind(socketListen, (sockaddr*)&addrSvr, sizeof(sockaddr)))
{
printf("bind error!\n");
return 0;
}

printf("listen,,,\n");
if(-1 == listen(socketListen, 5))
{
printf("listen error!\n");
return 0;
}

sockaddr addrClient;
socklen_t nLen = sizeof(sockaddr);

printf("accept...\n");
//int sockConn = accept(socketListen, (sockaddr*)&addrClient, &nLen);
int sockConn = accept(socketListen, NULL, NULL);
while(1)
{
printf("in while\n");
char bufRecv[1024] = {0};
int len = recv(sockConn, bufRecv, 1023, 0);
if(len <= 0)
break;

printf("%s\n", bufRecv);

send(sockConn, bufRecv, len, 0);
}
printf("over!\n");
close(sockConn);
close(socketListen);

return 0;
}



g++编译的

"close"在此作用域中尚未声明
naiveC 2011-06-01
  • 打赏
  • 举报
回复
::close(fd);
adamwyb 2011-06-01
  • 打赏
  • 举报
回复
我包含了socket头文件,之前的socket,bind,listen,accept全都能编译通过,我全部放在一个cpp文件中的,全部都在main函数里。
就想叫yoko 2011-06-01
  • 打赏
  • 举报
回复
你调用close()那个编译单元是不是没有包含socket的头文件~~~~~
ryfdizuo 2011-06-01
  • 打赏
  • 举报
回复
close在哪里定义的?

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧