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);
}
A few issues ...
printffor debug can interfere with the pipe data. Better to usestderr. A macro (e.g.prteanddbgprt) can helpcopyUsername, doingchar *&usernameis overly complicated. It can/should bechar *username.int &lengthis also complicated. Just pass backlengthas a return value.copyUsername, doingusername[strlen(username)] = '\0';is broken. It is a no-op. It is broken because it assumes the buffer is already 0 terminated. It is misplaced after theprintfReplace withusername[length] = 0;matchUsernamenot provided. I had to synthesize this.Here is the corrected code:
In the code above, I've used
cppconditionals to denote old vs. new code:Note: this can be cleaned up by running the file through
unifdef -kHere is the client code I synthesized to test the program:
Here is the server output with the command:
./client bork:Here is the server output with the command:
./client neo: