2017-02-13 133 views
1

我想知道一些示例程序,其中有一些中断或信号在两个线程之间进行通信。我冲浪并发现了一些系统调用,比如kill,tkill,tgkill和raise。但我的要求并不是要杀死进程应该像中断一样行事。在我的代码中,我有这个阻塞调用。如何在两个线程之间发送中断或信号?

fcntl(fd, F_SETFL,0); 
    read(fd,&dataReceived.Serial_input,1); 

任何与我的要求类似的示例代码。请做share.Thanks提前

我的代码:

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; 
    } 
    } 

接收FUNC:

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"); 
    } 
    } 
} 

我想从发送接收应当由串行函数处理函数信号。

+0

从长远来看,使用非阻塞IO和'select'会更快乐一点,但是对于已有的代码的最小更改,'tkill'就是您想要的 - 您只需为SIGUSR1安装一个_handler_ ',设置为_不重新启动_系统调用,并且在那里。 – zwol

+0

如何安装SIGUSR1处理程序? – Sri

+0

你应该可以自己回答这个问题。首先阅读'sigaction'手册页。 – zwol

回答

1

serial_function()您的serial_function()充满了对不是异步信号安全的函数的调用。它完全不适合用作信号处理程序或从一个被调用。

有可能建立一个线程,其中serial_function()按需异步运行,但似乎不符合您打断read()调用的目标。

您可能可能会设置一个信号处理程序,它自己通知serial_function()正在等待进行的线程,而不是在接收信号的线程中运行该函数。目前还不清楚这是否能满足您的需求。

或者,您可能会从您的read()中发现EINTR错误,并直接致电serial_function()作为回应。但是,请注意,如果read()已成功传输任何数据(在当前调用中),则此替代方法不会导致serial_function()运行。

在任何情况下,您都可以通过pthread_kill()在您选择的线索中发出信号,但在此之前您必须对策略进行整理。