我有一个用C编写的服务器程序,带有一个线程函数join_handler。当我在语句中调用此函数时 - printf("inside join handler %d",newsock);
在线程函数内执行。
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<pthread.h>
#define SERVER_PORT 5498
#define MAX_LINE 256
#define MAX_PENDING 5
#define MAXNAME 256
int req_no;
char packet_type[50];
//void* join_handler(struct*);
struct packet{
short type;
char data[MAXNAME];
};
struct packet packet_reg;
struct global_table{
int sockid;
int reqno;
};
struct global_table record[20];
void *join_handler(void *rec)
{
//pthread_mutex_t my_mutex= PTHREAD_MUTEX_INITIALIZER;
int *newsock;
newsock=(int*)rec;
printf("inside join handler %d",newsock); /// the last statement which gets executed
printf("\n %d",newsock);
if(recv(newsock,&packet_reg,sizeof(packet_reg),0)<0)
{
printf("\n Could not receive \n");
exit(1);
}
printf("\n joinhandler sockid is %d",newsock);
//other operation
pthread_exit(NULL);
}
int main(int argc, char* argv[])
{
pthread_t threads[2];
struct sockaddr_in sin;
struct sockaddr_in clientAddr;
char buf[MAX_LINE];
int s, new_s;
struct in_addr addr;
struct hostent *host;
int len;
struct registrationTable
{
int port;
char name[MAXNAME];
int req_no;
};
struct registrationTable table[10];
int *exit_value;
req_no=0;
char clientname[500];
/* setup passive open */
if((s = socket(PF_INET, SOCK_STREAM, 0)) < 0){
perror("tcpserver: socket");
exit(1);
}
/* build address data structure */
bzero((char*)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);
if(bind(s,(struct sockaddr *)&sin, sizeof(sin)) < 0){
perror("tcpclient: bind");
exit(1);
}
listen(s, MAX_PENDING);
/* wait for connection, then receive and print text */
while(1){
if((new_s = accept(s, (struct sockaddr *)&clientAddr, &len)) < 0){
perror("tcpserver: accept");
exit(1);
}
recv(new_s,&packet_reg, sizeof(packet_reg), 0);
if(recv(new_s,&packet_reg, sizeof(packet_reg), 0)<0)
{
printf("\n Could not receive first registration packet \n");
exit(1);
}
pthread_create(&threads[0],NULL,join_handler,new_s);
pthread_join(threads[0],&exit_value);
}
}
答案 0 :(得分:0)
直到\ n,你才会看到任何输出。 因此,您不会看到此行已执行:
printf("\n %d",newsock);
这并不意味着它不会执行,只是输出被缓冲,你不会看到它直到recv收到东西。但是,我的猜测是,直到你向客户端发回一些内容,因为你在启动线程之前读取了第一个数据包。