I have a server and a client, when I open the server I must open 2 Terminals, one for products selection and one for pay these products. I made this code for the client but I can't find out this: When I open the first client by typing ./client localhost
I want to select a product from the vending machine, once the product is selected I transfer the product using sockets to the server. Then when I open the second client ./client localhost
the server transfer the price to this second client and then I wrote a code for insert moneys. Once the product has been paid the second client leaves. Well I want that the first client wait the second, and only when the second leaves the first client leaves too. Should I use waitpid?
Thank you for your time, this is the code:
#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);
}
Clients are independent processes, which may run on different hosts. How can you use waitpid to control two processes on different hosts?
Lifecyle
[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