#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;
}
最佳答案
您要查找的调用是pthread_create()
。您应该离开并阅读 pthreads(例如 here ),然后尝试实现一些东西。
然后,当你有问题时,不需要整本书来回答,回来问它:-)
关于在c中为linux创建一个新线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034986/