シンプルなパイプを使用しています。私はしばらくの間、一度に1文字ずつ読みます。文字を読み取るたびに、何かを上書きすると思います
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main () {
int pipefd[2];
int cpid;
char buf[31];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("cpid");
exit(EXIT_FAILURE);
}
if (cpid == 0) { // child reads from pipe
close (pipefd[1]); // close unused write end
int i = 0;
while (read (pipefd[0], &(buf[i++]), 1)>0);
printf ("Server receives: %s", buf);
close (pipefd[0]);
exit (EXIT_SUCCESS);
}
else { // parent writes to pipe
close (pipefd[0]); // closing unused read end;
char buf2[30];
printf("Server transmits: ");
scanf ("%s", buf2);
write (pipefd[1], buf2, strlen(buf2)+1);
close(pipefd[1]);
wait(NULL);
exit(EXIT_SUCCESS);
}
return 0;
}
コードは修正されました。これは廃止されました:たとえば、「Flowers」と入力すると、F が出力され、その後 ~6 個の印刷不能文字が出力されます。
しかし、ちょっとした奇妙なことが起こっています.30よりも長い文字列を使用しただけで、エラーはまったく発生せず、文字列全体を書き込むことができました. 私の両方のバッファはそれよりもかなり小さいですが。