How to IPC between PHP clients and a C Daemon Server?

后端 未结 7 1094
春和景丽
春和景丽 2020-12-02 13:32

and thanks for taking a look at the question.

The background
I have several machines that continuously spawn multiple (up to 300) PHP console sc

7条回答
  •  佛祖请我去吃肉
    2020-12-02 14:17

    Here is a working example where the php script sends a request to a C daemon and then waits for the response. It uses Unix domain sockets in datagram mode so it is fast and simple.

    client.php

    
    

    server.c

    #include 
    #include 
    #include 
    
    #define SOCKET_FILE "/tmp/myserver.sock"
    #define BUF_SIZE    64 * 1024
    
    int main() {
      struct sockaddr_un server_address = {AF_UNIX, SOCKET_FILE};
    
      int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
      if (sock <= 0) {
          perror("socket creation failed");
          return 1;
      }
    
      unlink(SOCKET_FILE);
    
      if (bind(sock, (const struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
          perror("bind failed");
          close(sock);
          return 1;
      }
    
      while (1) {
        struct sockaddr_un client_address;
        int i, numBytes, len = sizeof(struct sockaddr_un);
        char buf[BUF_SIZE];
    
        numBytes = recvfrom(sock, buf, BUF_SIZE, 0, (struct sockaddr *) &client_address, &len);
        if (numBytes == -1) {
          puts("recvfrom failed");
          return 1;
        }
    
        printf("Server received %d bytes from %s\n", numBytes, client_address.sun_path);
    
        for (i = 0; i < numBytes; i++)
          buf[i] = toupper((unsigned char) buf[i]);
    
        if (sendto(sock, buf, numBytes, 0, (struct sockaddr *) &client_address, len) != numBytes)
          puts("sendto failed");
      }
    
    }
    

提交回复
热议问题