Linux Socket坏文件描述符

时间:2015-04-01 20:56:03

标签: c linux sockets

我找不到重复,所以我决定发帖。我们现在进入套接字(初学者级别),并获得以下代码,以便客户端使用send()recv()向服务器发送简单消息。但是,我尝试的所有内容似乎都没有摆脱error: Bad File Descriptor,而newsockfd始终返回值-1。我很困惑,不知道为什么它不起作用。

的defs.h

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

#define SERV_TCP_PORT 6000
#define SERV_HOST_ADDR  "127.0.0.1" 

char *pname;

client.c

#include "../defs.h"
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

main(argc, argv)
int argc;
char *argv[];
{
  int sockfd;
  struct sockaddr_in serv_addr;

  pname=argv[0];
  bzero((char*) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family=AF_INET;
  serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);
  serv_addr.sin_port=htons(SERV_TCP_PORT);
  if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0) {
    printf("client: can't open stream socket\n");
    exit(0);
  }
  if (connect(sockfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
    printf("client: can't connect to server\n");
    exit(0);
  }
 send(sockfd,"1",1,0);
  close(sockfd);
  exit(0);
}

server.c

#include "../defs.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <strings.h>
void error(char *msg)
{
    perror(msg);
    exit(1);
}
main(argc, argv)
int argc;
char *argv[];
{
  int sockfd,clilen, childpid;
 int newsockfd;
char buff[255];
  struct sockaddr_in cli_addr, serv_addr;
  if ((sockfd=socket(AF_INET,SOCK_STREAM, 0)) <0) {
    printf("server: can't open stream socket\n");
    exit(0);
  }
  bzero((char*) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family=AF_INET;
  serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
  serv_addr.sin_port=htons(SERV_TCP_PORT);

  if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
    printf("server: can't bind local address\n");
    exit(0);
  }
  listen(sockfd, 5);
  for ( ; ; ) {
    clilen=sizeof(cli_addr);
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
  printf("%d\n",newsockfd);
    if(newsockfd < 0) {
      printf("server: accept error\n");
    error("ERROR on accept");
      exit(0);
    }
    if((childpid=fork()) <0) {
      printf("server: fork error\n");
      exit(0);
    }
    else if (childpid==0) {
        close(sockfd);  
      recv(newsockfd,buff,sizeof(buff),0);
    }
    close(newsockfd);
  }
}

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

在孩子的代码中,您关闭 sockfd,代表服务器。但是在无限for循环的下一次迭代中,孩子也会运行,您尝试使用 accept() sockfd新客户。因此,sockfdBad file descriptor

删除代码中的close(sockfd);行,并在完全确定不再需要时将其关闭。