我不得不写一个程序,使用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;
}

它可以工作,但现在我必须在这里实现信号。在发送SIGUSR2信号之前,发送SIGUSR1信号应停止程序执行。
问题是,当我发送信号时,只有一个线程得到它。因此,我必须使用FIFO通知其他线程哪个信号被执行,并在其余线程中执行它。
我怎么能这样做?

最佳答案

信号传递给进程,而不是线程。因此,任何能够处理信号的线程都可以用来调用信号处理程序。您需要做的是找出如何处理该信号,然后决定如何将其传递给所有线程。你还没有真正描述“停止程序执行”是什么意思,所以我不得不猜测。
我建议使用pthread_sigmasksigwait的组合。您可以使用pthread_sigmask禁用工作线程中SIGUSR1和SIGUSR2的自动处理。然后在第四个信号处理线程中调用sigwait显式处理这些信号。当信号处理程序线程接收到SIGUSR1时,它设置一个全局标志。工作线程定期检查该标志并进入睡眠状态(条件变量可能?)当它设置好。然后,信号处理程序线程循环并再次调用sigwait。当它接收到SIGUSR2时,它会唤醒工作线程,然后循环并再次调用sigwait

关于c - 在三个线程之间发送信号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25752006/

10-11 22:23
查看更多