Reputation: 903
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!
Upvotes: 0
Views: 66
Reputation: 34585
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.
Upvotes: 1