使用管道进行线程通信的奇怪输出

时间:2014-06-20 13:56:04

标签: c linux multithreading

我有三个线程 - 第一个读取字符串,第二个计算字符,第三个显示它。我正在使用烟斗进行沟通。

然而,在运行之后没有任何反应,当我输入某些东西时,让我们说“asd”,我得到:

asd
asd
Enter the message: Enter the message:

asd
asd
Enter the message:

怎么了?

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

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

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

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

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

2 个答案:

答案 0 :(得分:1)

那是因为printf只将内容写入缓冲区。一旦收到换行符('\ n')或stdout被调用,该内容就会实际发送到fflush(stdout)

您可以尝试在flush(stdout);旁边添加printf("Enter the message: ");,您应该会看到自己的期望。

答案 1 :(得分:1)

您的代码中存在逻辑问题。在output

if (length < sizeof (count)) {    // not <=
成功写入整数后,

length总是等于sizeof (count)

另外,在while (1) {...}中包装所有功能并不是最安全的。删除while (1)循环并将其替换为函数末尾的返回值。即return ptr;例如:

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

        printf ("\noutput:\n\n");

//     while (1) {
        length = read (second[0], &count, sizeof (count));
        printf ("count: %d\n", count);

        if (length < sizeof (count)) {    // not <=
            printf ("closing second[0] and exiting\n");
            close (second[0]);
            exit (2);
        }

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