#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int acceptSocket;
struct sockaddr_in addr, server, client;
char buf[100];
long rc,sentbytes;
socklen_t len;
int port = 18227
int CreateSocket()
{
if(rc!=0)
{
printf("socket failure code: %ld\n",rc);
return 1;
}
else
{
printf("socket started!\n");
}
// Socket creation for UDP
acceptSocket=socket(AF_INET,SOCK_DGRAM,0);
if(acceptSocket==-1)
{
printf("Failure: socket creation is failed, failure code\n");
return 1;
}
else
{
printf("Socket started!\n");
}
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
addr.sin_addr.s_addr=inet_addr(INADDR_ANY);
rc=bind(acceptSocket,(struct sockaddr*)&addr,sizeof(addr));
if(rc== -1)
{
printf("Failure: listen, failure code:\n");
return 1;
}
else
{
printf("Socket an port %d \n",port);
}
while(rc!=-1)
{
len =sizeof(server);
rc=recvfrom(acceptSocket,buf, sizeof(buf), 0, (struct sockaddr*) &server, &len);
if(rc==0)
{
printf("Server has no connection..\n");
break;
}
if(rc==-1)
{
printf("something went wrong with data %s", strerror(errno));
break;
}
//for recieving the data
XcpIp_RxCallback( (uint16) rc, (uint8*) buf, (uint16) port );
makeTimer("First Timer", &firstTimerID, 2, 2); //2ms
makeTimer("Second Timer", &secondTimerID, 10, 10); //10ms
makeTimer("Third Timer", &thirdTimerID, 100, 100); //100ms
}
close(acceptSocket);
return 0;
}
int main()
{
Xcp_Initialize();
CreateSocket();
return 0;
}
我创建了一个服务器端程序,用于从客户端接收数据并将响应发送回客户端。有一些api,其定义未在上面显示。如果我运行上面的程序,那么在收到数据时会有一些阻塞。有人建议从while(rc!= -1)创建一个新线程来解决问题。那么有人可以帮我做这个吗?
现在我创建了一个线程,但它显示了一些错误。 ..... ...
else
{
void *thread1()
{
while(rc!=-1)
{
rc=recvfrom(acceptSocket,buf, 256, 0, (struct sockaddr*) &client, &len);
if(rc==0)
..... 。
int main()
{
pthread_t tid;
Xcp_Initialize();
CreateSocket();
pthread_create (&tid, NULL, thread1, NULL);
return 0;
}
答案 0 :(得分:3)
您正在寻找的电话是pthread_create()
。你应该离开并阅读pthreads(例如here),然后尝试实现某些东西。
然后,当你有问题时,它不会需要整本书来回答,请回来询问: - )