c - Strange output using pipes for thread communication -
i have 3 threads - first 1 reads string, sec counts characters, , 3rd displays it. i'm using pipes communication.
however, after running nil happens, , when type in something, let's "asd", get:
asd asd come in message: come in message:
or
asd asd come in message:
what's wrong?
#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 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); homecoming 0; }
you have logic problem in code. in output
:
if (length < sizeof (count)) { // not <=
length
equal sizeof (count)
on successful write of integer.
also, wrapping function in while (1) {...}
not safest. remove while (1)
loops , replace them homecoming @ end of function. i.e. return ptr;
example:
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] , exiting\n"); close (second[0]); exit (2); } printf ("number of characters: %d\n", count); // } homecoming ptr; }
c linux multithreading
No comments:
Post a Comment