簡體   English   中英

在三個線程之間發送信號

[英]Sending signals between three threads

我必須編寫一個使用3個線程的程序-一個讀取字母,第二個計數字符,第三個輸出它們。 這是代碼:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/stat.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>

int first[2];
int second[2];

void *input(void *ptr)
{
   char str[100];
   int length;

   while(1)
   {
      printf("Enter the message: ");
      fflush(stdout);
      length = read(STDIN_FILENO, str, sizeof(str));

      if(str[0] == ';')
         exit(2);

      if(length <= 0)
      {
         if(length == -1)
            perror("read");
         close(first[1]);
         exit(2);
      }

      if(write(first[1], str, length) != length)
      {
         perror("write");
         exit(2);
      }
   }
}

void *countChars(void *ptr)
{
   char str[100];
   int length, count = 0;

   while(1)
   {
      length = read(first[0], str, sizeof(str));
      if(length <= 0)
      {
         if(length == -1)
            perror("read");
         close(first[0]);
         close(second[1]);
         exit(2);
      }
      if(write(STDOUT_FILENO, str, length) != length)
      {
         perror("write");
         exit(2);
      }

      while(str[count] != '\n') count++;

      write(second[1], &count, sizeof(count));

      count = 0;
   }
}

void *output(void *ptr)
{
   int length, count = 0;

   while(1)
   {
      length = read(second[0], &count, sizeof(count));
      if(length < sizeof(count))
      {
         close(second[0]);
         exit(2);
      }

      printf("Number of characters: %d\n", count);
   }
}

int main()
{
   pthread_t t1, t2, t3;

   if(pipe(first) == -1)
   {
      printf("First pipe error");
      exit(1);
   }

   if(pipe(second) == -1)
   {
      printf("Second pipe error");
      exit(1);
   }

   pthread_create(&t1, NULL, input, NULL);
   pthread_create(&t2, NULL, countChars, NULL);
   pthread_create(&t3, NULL, output, NULL);

   pthread_join(t1, NULL);
   pthread_join(t2, NULL);
   pthread_join(t3, NULL);

   return 0;
}

它可以工作,但是現在我必須在這里實現信號。 發送SIGUSR1信號應停止程序執行,直到發送SIGUSR2信號為止。

問題是當我發送信號時,只有一個線程得到它。 因此,我必須使用FIFO來通知其他線程執行了哪個信號,並在其余線程中執行該信號。

我該怎么辦?

信號傳遞給進程,而不傳遞給線程。 因此,任何能夠處理信號的線程都可以用來調用信號處理程序。 您需要做的是弄清楚如何處理信號,然后決定如何將其傳達給所有線程。 您沒有真正描述“停止程序執行”的含義,所以我不得不猜測。

我建議結合使用pthread_sigmasksigwait 您可以使用pthread_sigmask禁用工作線程中對SIGUSR1和SIGUSR2的自動處理。 然后在第四個信號處理程序線程中調用sigwait來顯式處理那些信號。 當信號處理程序線程接收到SIGUSR1時,它將設置一個全局標志。 設置該線程時,工作線程會定期檢查該標志並進入睡眠狀態(可能在條件變量上?)。 信號處理程序線程然后循環並再次調用sigwait 當它收到SIGUSR2時,它將喚醒工作線程,然后循環並再次調用sigwait

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM