C-服务器/客户端,等待其他客户端然后退出

时间:2018-06-18 16:02:41

标签: c multithreading unix client wait

我有服务器和客户端,当我打开服务器时,我必须打开2个终端,一个用于产品选择,一个用于支付这些产品。我为客户制作了这段代码但我无法找到:当我通过键入./client localhost打开第一个客户端时,我想从自动售货机中选择一个产品,一旦选择了产品,我就转移了使用套接字到服务器的产品。然后,当我打开第二个客户端./client localhost时,服务器将价格转移到第二个客户端,然后我写了一个插入代码的代码。产品付款后,第二个客户离开。好吧,我希望第一个客户端等待第二个客户端,并且只有当第二个客户端离开第一个客户端时才会离开。我应该使用waitpid吗?

感谢您的时间,这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "funzioni.h"


#define PORT 3490
#define MAXDATASIZE 100


int main(int argc, char *argv[]) {
  int sockfd;// numbytes;
  //char buf[MAXDATASIZE];
  struct hostent *he;
  struct sockaddr_in their_addr; // informazioni sull’indirizzo di chi si connette
  if (argc != 2) {
    fprintf(stderr,"usage: client hostname\n");
    exit(1);
  }
  if ((he=gethostbyname(argv[1])) == NULL) { // ottiene le informazioni sull’host
    herror("gethostbyname");
    exit(1);
  }

 if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }
  their_addr.sin_family = AF_INET; // host byte order
  their_addr.sin_port = htons(PORT); // short, network byte order
  their_addr.sin_addr = *((struct in_addr *)he->h_addr);
  memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
  if (connect(sockfd, (struct sockaddr *)&their_addr,sizeof their_addr) == -1)
  {
    perror("connect");
    exit(1);
  }

  //When the server is running, if I open a client I want to select products, when I open an other client I want to pay.  
  // Read the number of client, the first connected receives f=1 and 
  // the second f=2, I managed this in the server code
  int received_int=0 ;
  int return_status = read(sockfd, &received_int, sizeof(received_int));
  if (return_status > 0) {
     fprintf(stdout, "Client # = %d\n", ntohl(received_int));
  }
  else {
      perror("read");
      exit(1);
  }

 //Open Client1 - Select product

  int f = ntohl(received_int);
  if(f==1){


       //CODE FOR THE FIRST CLIENT
       //Select product

  }


  //Open client2 - Pay
  if(f==2){

     // CODE FOR THE SECOND CLIENT
     //pay, insert money, confirm, take the product
  }

  exit(EXIT_SUCCESS);
}

1 个答案:

答案 0 :(得分:1)

客户端是独立进程,可以在不同的主机上运行。如何使用 waitpid 来控制不同主机上的两个进程?

生命周期

[1] Client1:
    send selection info to server
[2] Server:
    notify client2
[3] Client2:
    Send payment info to server (and exit???)
[4] Server:
    notify client1
[5] Client1:
    Exit