gpt4 book ai didi

c - 使用管道在线程之间发送数据

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:23 24 4
gpt4 key购买 nike

我有 3 个线程 - 我必须在第一个线程中读取内容,在第二个线程中计算字符数,并在第三个线程中进行输出。所以我在这里使用两个管道;对于第 1-2 个线程,以及第 2-3 个线程。

然而,它根本不起作用。我的意思是,我可以在控制台中输入字符串,但是什么也没有发生,没有输出。

这里有什么问题吗?

此外,是否可以在某处的第一个线程中添加类似“在此处输入字符串:”之类的内容?将它添加到 while 循环中似乎会产生奇怪的结果 - 它在运行程序后随机显示 :P

代码如下:

#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)
{
while(1)
{
char str[100];
int result;

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

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

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

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

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

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

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

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

printf("Writer: %d\n", count - 1);
}
}

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

最佳答案

您希望 countChars 函数计数到换行符并写入 int "count"

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

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

if(write(STDOUT_FILENO, str, result) != result)
{
perror("write");
exit(2);
}

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

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

count = 0;
}
}

output 函数将 int 的大小读入 int 变量。

void *output(void *ptr)
{
int result2, count = 0;
//char str[100];

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

printf("Writer: %d\n", count);
}
}

这工作正常,因为只有 countChars 正在写入第二个管道。管道写入/读取对于 PIPE_BUF 字符是原子的,而 int 比它少得多,因此读取是可预测的。

关于c - 使用管道在线程之间发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com