Skip to content

Instantly share code, notes, and snippets.

@mkusher
Last active August 29, 2015 14:03
Show Gist options
  • Save mkusher/86f949a5f61d7e8d7f5b to your computer and use it in GitHub Desktop.
Save mkusher/86f949a5f61d7e8d7f5b to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
char pathname[] = "channel.fifo.out";
int file=0;
bool is_equal(char * str1, char * str2, int length){
for(int i = 0; i<length ; ++i){
if(str1[i] != str2[i])
return false;
}
return true;
}
void * thread1(void * fake){
char write_str[8] = "thread1";
char read_str[8];
size_t size;
usleep(1);
while(1){
size = write(file, write_str, 8);
if(!size){
printf("Write error1\n");
}
size = read(file, read_str, 8);
read_str[7]=0;
if(size!=8){
printf("Read error1\n");
}
else {
printf("from thread2: %s\n", read_str);
}
}
}
void * thread2(void * fake){
char write_str[8] = "thread2";
char read_str[8];
size_t size;
while(1){
size = write(file, write_str, 8);
if(!size){
printf("Write error2\n");
}
size = read(file, read_str, 8);
read_str[7]=0;
if(size!=8){
printf("Read error2\n");
}
else{
printf("from thread1: %s\n", read_str);
}
}
}
pthread_t create1(){
pthread_t thid;
int result;
int *fakenum = NULL;
result = pthread_create(&thid, (pthread_attr_t *)NULL, thread1, NULL);
if(result != 0) {
printf("Error on thread create, return value = %d\n", result);
exit(-1);
}
return thid;
}
pthread_t create2(){
pthread_t thid;
int result;
int *fakenum = NULL;
result = pthread_create(&thid, (pthread_attr_t *)NULL, thread2, NULL);
if(result != 0) {
printf("Error on thread create, return value = %d\n", result);
exit(-1);
}
return thid;
}
int main(){
if(mkfifo(pathname, O_RDWR | 0666) < 0){
printf("Error creating fifo!\nError: %s\n", strerror(errno));
exit(-1);
}
if((file = open(pathname, O_RDWR)) < 0){
printf("Error creating file!\nError: %s\n", strerror(errno));
exit(-1);
}
pthread_t thid1 = create1();
pthread_t thid2 = create2();
pthread_join(thid1, (void **)NULL);
pthread_join(thid2, (void **)NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment