gpt4 book ai didi

c - 定时器触发新线程时的 tcp 通信问题

转载 作者:行者123 更新时间:2023-11-30 17:16:24 25 4
gpt4 key购买 nike

这是庞大代码的一部分,我在其中与机器人和 s7 plc 通信,两者并行工作。问题是,之前我认为问题是 plc 通信的一部分,但现在我已将所有代码减少到客户端服务器应用程序,这似乎也失败了。该代码基本上按以下方式工作;每 50 毫秒客户端向服务器发送一条“hello”消息。当发送 20 条消息时,启动 7 秒的计时器。当计时器被触发时,第二个线程启动,该线程更改变量 f=1 并完成。与此同时,主程序将打印 hello,但是当变量 f 更改为 1 时,它应该只打印“aaaaa”,但它永远不会发生。

对于 PLC,问题是段错误。我的想法是 TCP 通信失败(为什么?)并且 PLC 阻止访问。我在移动机器人 ARM 之前尝试了相同的程序,并使用wireshark进行分析,您可以看到TCP是如何一直发送的,但是机器人再次停止了。最后,通过这个客户端应用程序,可以看到它们是如何没有按预期工作的。

希望大家能够帮助我。

非常感谢;)

客户

#include <stdlib.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h> // Primitive System Data Types
#include <errno.h> // Errors */
#include <sys/wait.h> // Wait for Process Termination
#include "plc_interface.h"
#include <netinet/in.h>
#include <time.h>
#include <signal.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/socket.h>

timer_t firstTimerID;
timer_t secondTimerID;
struct itimerspec it;
int t_block3=5;
pthread_t thread_robot;
pthread_attr_t thread_attr;
int res, z;
int f=0;



//THREAD FUNCTION ONCE THE REQUIRED BLOCK IS DETECTED
void *detection_robot(){
printf("First\n");
//f==1 to send the message aaaaaa
f=1;
pthread_exit(NULL);

}


int setTimer(timer_t * timerID, int time) {
struct itimerspec its;
//Interval for starting again
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
//Timer time
its.it_value.tv_sec = time;
its.it_value.tv_nsec = 0;
//Arm/disarmer a per process time
timer_settime (*timerID, 0, &its, NULL);

return 0;
}

//TIMER INTERRUPTION
static void timerHandler (int sig, siginfo_t * si, void *uc_) {
timer_t *tidp;
int iret;
tidp = si->si_value.sival_ptr;

//Initializes the attributes for the thread
res= pthread_attr_init(&thread_attr);
res=pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);

if (*tidp == firstTimerID) {
printf ("First timer\n");

//New thread to detect the second detection sensor
iret = pthread_create( &thread_robot, &thread_attr, detection_robot, NULL);
if(iret)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret);
exit(EXIT_FAILURE);
}
} else if (*tidp == secondTimerID) {
printf ("Second timer\n");
}

z--;

}


//ARM THE TIMERS
static int makeTimer (timer_t * timerID) {
struct sigevent te;
struct sigaction sa;
int sigNo = SIGRTMIN;
// Set up signal handler.
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = timerHandler; //Action when singal is triggered
sigemptyset (&sa.sa_mask);
if (sigaction (sigNo, &sa, NULL) == -1) {
perror ("sigaction");
}
// Set and enable alarm
te.sigev_notify = SIGEV_SIGNAL; //Gnerate alarm upon expiration
te.sigev_signo = sigNo; //SIGALRM
te.sigev_value.sival_ptr = timerID; //Timer ID
//Create a per_process timer using the timer ID
timer_create (CLOCK_REALTIME, &te, timerID);
return 0;
}


int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[6]={'h','e','l','l','o','\0'};
char message2[6]={'a','a','a','a','a','\0'};
char server_reply[2000];
//Initialize the timers
makeTimer(&firstTimerID);
makeTimer(&secondTimerID);

//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");

server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );

//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
int i=0;
while(1){
//Send hello every 50ms
if( send(sock , message , 6 , 0) < 0)
{
puts("Send failed");
return 1;
}
i++;
if (i==20){
setTimer (&firstTimerID, t_block3);
i=0;
}

//f-> 1, send aaaaaa when timer is triggered, but here is when it get stacked
if (f==1) {
f=0;
if( send(sock , message2 , 6 , 0) < 0)
{
puts("Send failed");
return 1;
}}

usleep(500000); //500ms
}

}

服务器

 
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write

int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , read_size;
struct sockaddr_in server , client;
char client_message[2000];

//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");

//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );

//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");

//Listen
listen(socket_desc , 3);

//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);

//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");

while(1){
//Receive a message from client
recv(client_sock , client_message , 2000 , 0);
printf("%s\n", client_message);

}

}

最佳答案

问题在于分配:

f = 1;

对其他线程不可见,因此 main() 线程永远看不到更改。要更正,您将需要使用同步机制,例如 pthread_mutex_t ,在读取或写入 fatomic_int 时必须获取该值。如果您的编译器支持 C11。

关于c - 定时器触发新线程时的 tcp 通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com