首页 > 解决方案 > 无法在嵌入式平台上的套接字上运行 fcntl

问题描述

我在一个嵌入式平台上工作,我遇到了一些(看似)基本套接字操作的问题。我想打开一个套接字并设置它O_NONBLOCK。我想出了以下示例代码:

  #include <stdio.h>
  #include <errno.h>
  #include <string.h>
  #include <unistd.h>
  #include <fcntl.h>
  #include <arpa/inet.h>

  char *host = "10.10.100.1";
  int port = 21;
  int control_fd = -1;
  int code;
  char *hostname;
  static struct sockaddr_in hisctladdr;

char *test(char *host, int port);

char *test(char *host, int port) {
  static char hostnamebuf[256];
  int iSockFlags;

  if (inet_aton(host, &hisctladdr.sin_addr))
  {
    hisctladdr.sin_family = AF_INET;
    hisctladdr.sin_port = htons(port);
    strncpy(hostnamebuf, host, sizeof(hostnamebuf));
    hostnamebuf[sizeof(hostnamebuf) - 1] = 0;
  }
  else
  {
    iprintf("Ftp::test IP dot format required\n");
    code = -1;
    return (NULL);
  }
  hostname = hostnamebuf;
  control_fd = socket(hisctladdr.sin_family, SOCK_STREAM, 0);
  if (control_fd < 0)
  {
    iprintf("Ftp::test socket\n");
    code = -1;
    close(control_fd);
    control_fd = -1;
    return (NULL);
  }

  iSockFlags = fcntl(control_fd, F_GETFL, 0);
  if (iSockFlags == -1) {
    iprintf("Ftp::test : F_GETFL on %d failed, errno %d\n",control_fd,errno);
    return (NULL);
  }
  int flags = fcntl(control_fd, F_GETFL, 0);
  if (flags ==-1) {
          iprintf("Ftp::test unable to get flags, errno %d\n",errno);
          return(NULL);
  }
  iprintf("current flags 0x%x\n",flags);
  if (flags & O_NONBLOCK)
          iprintf("O_NONBLOCK already set 0x%x\n",flags);
  else {
          iprintf("set O_NONBLOCK 0x%x\n",O_NONBLOCK);
          flags |= O_NONBLOCK;
          iprintf("flags 0x%x\n",flags);
          if(fcntl(control_fd, F_SETFL, flags)<0) {
                  iprintf("Error, could not set O_NONBLOCK, errno %d\n",errno);
                  return(NULL);
          }
  }
  return (NULL);
}

void main(void){
  test(host,port);
}

这似乎在我的 PC 上按预期工作,但在嵌入式目标平台上的工作方式似乎不同。在目标上,我看到以下消息:Ftp::test : F_GETFL on 15 failed, errno 88并且 errno 88 是“非套接字上的套接字操作”。我想知道为什么会这样?我们正在运行以下内核:

# uname -s    
Linux
# uname -r
4.1.18-gbbe8cfc

ARMv7 Processor rev 2 (v7l)CPU上

根据下面@Shawn 的评论,socket.h我使用的标头 ( fns_socket.h) 仅包含以下套接字类型:

#define SOCK_STREAM     1       /* virtual circuit */
#define SOCK_DGRAM      2       /* datagram */
#define SOCK_RAW        3       /* raw socket */
#define SOCK_RDM        4       /* reliable-delivered message */
#define SOCK_SEQPACKET  5       /* sequenced packet */
#define SOCK_PACK_EX    6       /* packet exchange non Berkeley */

SOCK_NONBLOCK在创建时设置标志,不幸的是对我不起作用。

标签: linuxsocketsembeddedfcntl

解决方案


推荐阅读