hi, i'm developing a school project but i'm facing an error that i can't resolve.
when i write in console anything to a fifo, the program read it and it should add it to the list.
But it losses the item added to the list at the end of the function [insert_tail]
Code:
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h> // POSIX Threads
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#define FIFO_THREADS_MAX 4
#define LIST_THREADS_MAX 3
#define MAX_BUF_SIZE 255
#define fifo1 "FIFO_ae1"
#define fifo2 "FIFO_ae2"
#define fifo3 "FIFO_ae3"
#define fifo4 "FIFO_ae4"
#define fifoOut "FIFO_out"
struct s_toll {
char* carRegistration;
struct s_toll *next;
};
typedef struct s_toll toll;
toll *toll_head_1 = NULL;
toll *toll_head_2 = NULL;
toll *toll_head_3 = NULL;
int fileExists(char * fileName);
void createFifo(char * path);
void *function(void *param);
toll** getSmallestToll();
void insert_tail(toll **head, char *carRegistration);
int main(void) {
pthread_t threads[FIFO_THREADS_MAX];
char* thread_args[FIFO_THREADS_MAX];
int i;
createFifo(fifo1);
createFifo(fifo2);
createFifo(fifo3);
createFifo(fifo4);
createFifo(fifoOut);
toll_head_1 = toll_head_2 = toll_head_3 = NULL;
for (i = 0; i < FIFO_THREADS_MAX; i++) {
if (i == 0)
thread_args[i] = fifo1;
else if (i == 1)
thread_args[i] = fifo2;
else if (i == 2)
thread_args[i] = fifo3;
else if (i == 3)
thread_args[i] = fifo4;
pthread_create(&threads[i], NULL, function, &thread_args[i]);
}
for (i = 0; i < FIFO_THREADS_MAX; i++) {
pthread_join(threads[i], NULL);
}
return EXIT_SUCCESS;
}
int fileExists(char * fileName) {
struct stat buf;
int i = stat(fileName, &buf);
if (i == 0) {
return 1;
}
return 0;
}
void createFifo(char * path) {
if (fileExists(path) == 1) {
printf("FIFO %s ja existe!\n", path);
return;
}
if (mkfifo(path, 0666) != 0) {
printf("mkfifo() error creating %s \n", path);
} else {
printf("FIFO %s created with sucess! \n", path);
}
}
void *function(void *param) {
char* pipe = *((char **) (param));
char buf[MAX_BUF_SIZE];
int fd, numread;
printf("thread with pipe %s\n", pipe);
while (strcmp(buf, "fim\n") != 0) {
fd = open(pipe, O_RDONLY);
numread = read(fd, buf, MAX_BUF_SIZE);
buf[numread] = '\0';
char *carRegistration= buf;
insert_tail(getSmallestToll(), carRegistration);
}
printf("FIFO %s ended\n", pipe);
pthread_exit(NULL);
}
void insert_tail(toll **head, char *carRegistration) {
toll *currentnode;
toll *newCar = (toll*) malloc(sizeof (toll));
if (newCar == NULL)
return;
newCar->carRegistration = carRegistration;
newCar->next = NULL;
if (*head == NULL)
*head = newCar;
else {
currentnode = head;
while (currentnode->next != NULL)
{
currentnode = currentnode->next;
}
currentnode->next = newCar;
}
}
toll** getSmallestToll() {
return &toll_head_1;
// todo
}
If anyone can help...
Thanks