想要建立服务器-客户端连接。我想将 2 个或更多客户端的数据发送到服务器。服务器需要收集所有这些数据并将其写入数据库。问题是,如何使用 fork()、getppid?得到皮德?等待()?如何避免僵尸等。
int main( void )
{
pid_t client_pid;
pid_t wait(int *status);
Socket server, client;
int bytes;
// open server socket
server = tcp_passive_open( PORT );
while( 1 ) {
client = tcp_wait_for_connection( server );
//create new process
client_pid = fork();
printf("%d",client_pid);
//client must have id
if(client_pid >= 0){
if(client_pid > 0){ //server
}else{ //client
bytes = tcp_receive( client, buffer, BUFSIZE);
printf("received message of %d bytes: %s\n", bytes, buffer);
// echo msg back to client
char buffer[] = "Send data ....put data here";
tcp_send( client, (void*)buffer, bytes);
//sleep(1); /* to allow socket to drain */
tcp_close( &client );
}
}
}
tcp_close( &server );
return 0;
}
对于客户,我写了这个:
#define BUFSIZE 1024
#define SERVER_IP "127.0.0.1"
#define PORT 1234
unsigned char buffer[BUFSIZE];
int main( void ) {
Socket client;
int ret;
char msg[] = "Hello there! Anyone?";
// open TCP connection to the server; server is listening to SERVER_IP and PORT
client = tcp_active_open( PORT, SERVER_IP );
// send msg to server
tcp_send( client, (void *)msg, strlen(msg)+1 );
// get reply from server
printf("\nanswer from server: ");
while ( (ret = tcp_receive (client, buffer, BUFSIZE)) > 0 ) {
printf("%s", buffer);
}
printf("\n");
// exit
tcp_close( &client );
return 1;
}
有人可以帮帮我吗?知道如何使用这些进程、线程等的任何好的教程吗?
谢谢!!