I' ll attach here the code I wrote, it doesn't work the way it should, it doesn't read properly from fifo. It was sending the username correctly before adding more code, it makes me think I wrote the code bad from beginning. If it's helpful I'll post the client code too, but I think the problem is here. When I run the program it prints the length correctly, but it doesn't print the username at all.
//SERVER
void copyUsername(int fd, char *&username, int &length)
{
printf("Waiting for client login...\n");
if (read(fd, &length, sizeof(int)) == -1)
{
printf("Could not read in the fifo 1\n");
return;
}
printf("Client wrote an username\n");
printf("%d\n", length);
if (read((char)fd, &username, sizeof(char)* length) == -1)
{
printf("Could not read in the fifo 2\n");
return;
}
printf("%s\n", username);
username[strlen(username)] = '\0';
printf("Copied successfully from FIFO %s\n", username);
}
int main()
{
if (mkfifo("fifo1", 0666) == -1)
{
if (errno != EEXIST)
{
printf("Could not create fifo file\n");
return 1;
}
}
int fd = open("fifo1", O_RDWR);
if (fd == -1)
{
printf("Could not open fifo file\n");
return 2;
}
char *username;
int length;
bool connected;
int pfd[2];
if(pipe(pfd) == -1)
{
printf("Could not open the pipe\n");
return 3;
}
int id = fork();
if(id == -1)
{
printf("Could not execute the fork\n");
return 4;
}
if(id == 0)
{
// child process
close(pfd[0]);
copyUsername(fd, username, length);
bool match = matchUsername(username, length);
write(pfd[1], &match, sizeof(match));
close(pfd[1]);
exit(0);
}
else
{
// parent process
close(pfd[1]);
read(pfd[0], &connected, sizeof(connected));
close(pfd[0]);
wait(NULL);
}