0

そこで、mkfifo() を使用して C で基本的な FIFO パイプラインを実装しようとしています。これまでの私のコードクラスは次のとおりです。

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;
}

サーバー.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;
}

現在、パイプラインは機能していますが、何らかの理由でサーバーはメッセージの一部しか受信していません。たとえば、プロトコルから「HELLO WORLD」という文字列を取得すると、次の出力が得られます。

Server receive: HELLO WO
Client send: HELLO WORLD

サーバーはメッセージ全体を受信する必要がありますが、そうではありません。私は何を間違っていますか?助けてくれてありがとう!

4

1 に答える 1

1

openreadとからの戻り値の通常は不可欠なチェックを怠っていることに気付きwriteました。持っていた場合は、この行のエラーに気付いたかもしれません

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

stringはポインターであるため、8 バイト (ポインターのサイズ) を送信しています。ターミネータを送信する必要があるかどうかに応じて、strlen(string)または thatを使用する必要があります。+1

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

最近の賢明でない編集で間違いを繰り返します。

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

オリジナルに固執し、#defineそれをバッファ割り当てと読み取り要求サイズの両方に使用することをお勧めします。

于 2016-06-02T18:06:00.047 に答える