4

我只是尝试了一个非常简单的示例来开始使用套接字在 C 应用程序和 Python 之间进行通信。这是一个非常简单的 Python 脚本:

import socket

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/demo_socket")
print "Sending..."
s.send("Hello C from Python!")
data = s.recv(1024)
s.close()
print 'Received', repr(data)

这里是相应的 C 代码,没有标题:

int main(void)
{  
  struct sockaddr_un address;
  int socket_fd, connection_fd;
  socklen_t address_length;
  pid_t child;  

  char buffer[256];
  int n;

  socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
  if (socket_fd < 0){
      printf("socket() failed\n");
      return 1;
  } 

  unlink("/tmp/demo_socket");
  memset(&address, 0, sizeof(struct sockaddr_un));

  address.sun_family = AF_UNIX;
  snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/demo_socket");

  if (bind(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0) {
      printf("bind() failed\n");
      return 1;
  }
  if(listen(socket_fd, 5) != 0) {
      printf("listen() failed\n");
      return 1;
  }

  address_length = sizeof(address);  
  while((connection_fd = accept(socket_fd, 
                   (struct sockaddr *) &address,
                   &address_length)) > -1)
  {
      printf("successfully received data\n");
      bzero(buffer,256);
      n = read(connection_fd,buffer,255);
      if (n < 0) error("ERROR reading from socket");
         printf("Here is the message: %s\n\n", buffer);
      strcpy(buffer, "Hi back from the C world"); 
      n = write(connection_fd, buffer, strlen(buffer));
      if (n < 0) 
         printf("ERROR writing to socket\n");           
      break;      
  }
  close(socket_fd);
  close(socket_fd);
  return(0);
}

并行运行时输出如下:

 Successfully received data
 Here is the message: Hello C from Python!

 ERROR writing to socket
 close failed in file object destructor:
 Error in sys.excepthook:

 Original exception was:

所以好消息是,从 Python 世界接收东西可以正常工作,但是当我试图写回一些东西时,我得到了一个错误,而且我最终似乎得到了一个例外。有人知道我在这里做错了什么吗?

编辑:谢谢大家,我做了你建议的更正,消息交换工作正常,只是 C 应用程序仍然造成问题,我不知道为什么......

close failed in file object destructor:
Error in sys.excepthook:

Original exception was:
4

2 回答 2

8

您正在尝试写入侦听套接字

write(socket_fd, buffer, strlen(buffer));

你应该试试

write(connection_fd, buffer, strlen(buffer));
于 2012-11-07T12:13:10.963 回答
0

您收到警告是因为您关闭了两次 socket_fd。

于 2014-07-06T11:00:50.117 回答