我想知道一些示例程序,其中一些中断或信号在两个线程之间进行通信。我已经上网并找到了一些系统调用,如 kill、tkill、tgkill 和 raise。但我的要求不是终止进程它应该表现为中断。在我的代码中,我有这个阻塞调用。
fcntl(fd, F_SETFL,0);
read(fd,&dataReceived.Serial_input,1);
任何与我的要求相似的示例代码。请分享。提前致谢
我的代码:
void *serial_function(void *threadNo_R)
{
int ImThreadNo = (int) threadNo_R;
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);//
if (fd == -1)
{
/* Could not open the port. */
perror("open_port: Unable to open /dev/ttyUSB1 - ");
}
fcntl(fd, F_SETFL,0);
while(1)
{
read(fd,&dataReceived.Serial_input,1);
printf("\n From serial fn: Serial_input is:%c\n",dataReceived.Serial_input);
dataReceived.t2=dataReceived.Serial_input;
if(V_buf.power_window_data.front_right_up>=1)
{
sprintf(cmd,"Window is raising=%d",V_buf.power_window_data.front_right_up);
do
{
writenornot = write( fd, &cmd[spot], 1 );
spot++;
} while (cmd[spot-1] != '\0' );
spot=0;
//
if (writenornot < 0)
{
printf("Write Failed \n");
}
else
printf("Write successfull \n");
// write( fd,"DOWN",4);
}
print_screen=1;
}
}
接收函数:
void *receive_function(void *threadNo_R)
{
int ImThreadNo = (int) threadNo_R;
while(1)
{
if(msgrcv(R_msgid,&V_buf,sizeof(struct vehicle)+1,1,0) == -1)
{
printf("\n\nError failed to receive:\n\n");
}
}
}
我想从应该由串行函数处理的接收函数发送信号。
最佳答案
您的 serial_function()
充满了对非异步信号安全函数的调用。它完全不适合用作信号处理程序或被信号处理程序调用。
可以设置一个线程,让 serial_function()
按需异步运行,但这似乎无法满足您中断 read()
的目标> 打电话。
您可以设置一个信号处理程序,它本身会通知 serial_function()
正在等待继续的线程,而不是在接收信号的线程中运行该函数。尚不清楚这是否会满足您的需求。
或者,您可能会从 read()
中捕获 EINTR
错误,并直接调用 serial_function()
作为响应。但是请注意,如果 read()
在成功传输任何数据(在当前调用中)后被中断,则此替代方法不会导致 serial_function()
运行.
在任何情况下,您都可以通过 pthread_kill()
在您选择的线程中发出一个信号,但您必须先确定您的策略才能发挥作用。
关于c - 如何在两个线程之间发送中断或信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42203973/