PDA

View Full Version : [C++] problema fork


jk-koldus
30-05-2007, 12:19
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>

#define LISTEN_PORT 9800
#define BACKLOG 1

void relazione(int new_fd,int bytes_recv,pid_t pid);

main() {
int sockfd, new_fd, len, bytes_sent, bytes_recv, connessione, sin_size;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
char buff[512] = {0};
pid_t pid;

sockfd = socket(AF_INET, SOCK_STREAM, 0);


my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(LISTEN_PORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(my_addr.sin_zero), '\0', 8);

//bind sulla porta
connessione = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));

while(!connessione) {

listen(sockfd, BACKLOG);
sin_size = sizeof(struct sockaddr_in);
new_fd = accept(sockfd, (struct sockaddr *)&their_addr,&sin_size);
char *msgtoclient="Connesso..";
len = strlen(msgtoclient);
bytes_sent = send(new_fd,msgtoclient, len, 0);
if (pid = fork()) {
relazione(new_fd,bytes_recv,pid);
}

}

}

void relazione(int new_fd, int bytes_recv,pid_t pid) {

while (new_fd) {

int len, bytes_sent;
char buff[512] = {0};
bytes_recv = recv(new_fd, buff, sizeof(buff)-1,0);
buff[512]='\0';
if (!bytes_recv) { new_fd = 0; }
if (strncmp(buff,"prova",5)==0) {
char *msgtoclient="Prova andata!";
len = strlen(msgtoclient);
bytes_sent = send(new_fd, msgtoclient, len, 0);
} else if (strncmp(buff,"disconnect",10)==0) {
char *msgtoclient="Disconnessione in corso..";
len = strlen(msgtoclient);
bytes_sent = send(new_fd, msgtoclient, len, 0);
new_fd = 0;
break;
} else {
char *msgtoclient="Comando inesistente..";
len = strlen(msgtoclient);
bytes_sent = send(new_fd, msgtoclient, len, 0);
}

}

}


questo è il programma che ho fatto...dovrebbe accettare le connessioni da un client interpretare i dati e rispondere.. soltante che non mi termina i vari fork che si vengono a creare... qualche suggerimento, consiglio??