首页 > 解决方案 > C-服务器/客户端,等待另一个客户端然后退出

问题描述

我有一个服务器和一个客户端,当我打开服务器时,我必须打开 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);
}

标签: cmultithreadingunixclientwait

解决方案


客户端是独立的进程,可能运行在不同的主机上。如何使用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

推荐阅读