[英]Strange output using pipes for thread communication
我有三個線程-第一個線程讀取一個字符串,第二個線程計算字符,第三個顯示它。 我正在使用管道進行通信。
但是,運行它之后什么也沒有發生,當我輸入內容時,我們說“ 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;
}
那是因為printf只將內容寫入緩沖區。 一旦收到換行符('\\ n')或調用了fflush(stdout)
,內容就會實際發送到stdout
。
您可以嘗試添加flush(stdout);
在printf("Enter the message: ");
旁邊printf("Enter the message: ");
,您應該會看到期望的結果。
您的代碼中存在邏輯問題。 在output
:
if (length < sizeof (count)) { // not <=
成功寫入整數時, length
將始終等於sizeof (count)
。
同樣,將所有功能包裝在while (1) {...}
中也不是最安全的。 刪除while (1)
循環,並在函數末尾用return代替它們。 即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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.