0

So I'm trying to implement a basic FIFO pipeline in C using mkfifo(). Here are my code classes so far:

main.c:

int main(int argc, char *argv[]) {
char *path = "/tmp/fifo";
pid_t pid;

setlinebuf(stdout);
unlink(path);
mkfifo(path, 0600);

pid = fork();
if (pid == 0) {
    client(path);
} else {
    server(path);
}

return(0);
}

client.c:

void client(char *path) {

char *input;
input = (char *)malloc(200 * sizeof(char));

read(STDIN_FILENO, input, 200);

struct Message message;
message = protocol(input); //protocol simply takes an input string and formats it
char number = message.server;
char* string;
string = message.string;

int fd;

fd = open(path, O_WRONLY);
write(fd, string, sizeof(string));
printf("Client send: %s\n", string);
close(fd);


return;
}

server.c:

void server(char *path) {
int fd;
char *input;
input = (char *)malloc(200 * sizeof(char));

fd = open(path, O_RDONLY);
read(fd, input, sizeof(input));
printf("Server receive: %s\n", input);
close(fd);

return;
}

Now the pipeline is working, but for some reason the server only receives part of the message. For example if we get the following string from the protocol: "HELLO WORLD" We get the following output:

Server receive: HELLO WO
Client send: HELLO WORLD

The server should receive the whole message, but it isn't. What am I doing wrong? Thank you for any help!

keenns
  • 863
  • 4
  • 14
  • 26
  • In server.c, why `input = (char *)malloc(200 * sizeof(char));` but then `read(fd, input, MAX_BUF);` when `MAX_BUF` is 1024? – Weather Vane Jun 02 '16 at 17:51
  • Oh right I was trying various things, and both having that MAX_BUF or using sizeof(input) gave me the same output. Guess I forgot to change it back to something consistent! ^^; – keenns Jun 02 '16 at 17:59

1 Answers1

1

I notice you have skimped the usually essential checking of return values from open and read and write. If you had, you might have noticed the error in this line

write(fd, string, sizeof(string));

Because string is a pointer, you are sending 8 bytes (the size of the pointer). You should use strlen(string) or that +1, depending on whether the terminator needs to be sent.

write(fd, string, strlen(string));

You repeat the mistake in your recent unwise edit:

read(fd, input, sizeof(input));

You would be better sticking with the original #define and using that for both buffer allocation and read request size.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Thank you so much! I'm still very new to C. Using strlen and going back to my previous MAX_BUF did the trick!! – keenns Jun 02 '16 at 18:19
  • Please try to avoid in-line hard coded magic numbers - always source them from a single definition. – Weather Vane Jun 02 '16 at 18:21