Answer the question
In order to leave comments, you need to log in
How to setup select function on channels?
Hello.
Help, please, with the call to select - I have two files in the directory created with mkfifo - in1 and in2. And I write to them using echo echo "hi"> in1
, I want to be able to simultaneously write something to these files and read from them.
I do echo "hey"> in1
and I see
Descriptor f1 = 3
Descriptor f2 = 4
temp = 56
temp = 53
temp = 73
send f1 = 3
Descriptor f1 = 5
Descriptor f2 = 6
temp = 56
temp = 53
temp = 73
send f1 = 5
void read_and_calc(int fd) {
char buf[100];
int bytes = read(fd, buf, 100);
int temp = 0;
int i;
for(i = 0; i < strlen(buf) - 1; i++) {
int temp = buf[i] - '0';
sum += temp;
printf("temp = %d \n", temp);
}
buf[bytes] = 0;
}
while(1) {
int f1 = open("./in1", O_NONBLOCK | O_RDONLY);
int f2 = open("./in2", O_NONBLOCK | O_RDONLY);
if(!(f1 && f2)) {
printf("%d\n", sum);
return 0;
}
FD_ZERO(&read_set);
FD_SET(f1, &read_set);
FD_SET(f2, &read_set);
int pipe_num = select(f2 + 1, &read_set, NULL, NULL, NULL);
if(pipe_num > 0){
if (FD_ISSET (f1, &read_set)){
read_and_calc(f1);
printf("send f1 = %d\n", f1);
}
else if (FD_ISSET (f2, &read_set)){
read_and_calc(f2);
printf("send f2 = %d\n", f2);
}
}
}
Answer the question
In order to leave comments, you need to log in
It's not like that, you just don't understand what's going on. Firstly, files are opened in an endless loop, which is most likely not meant, they must be opened once. Secondly
, it will not work, because if it fails, open() returns -1. Thirdly, you use strlen for the contents of a buffer that was received by a non-string function and most likely does not contain '\0' (buf[bytes] = 0 should have been written before strlen).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question