次のコードに問題があります。フォークの使用 (プロセスの作成) に関するラボの割り当てを行っています。キーボードから入力を読み取り、FIFO に読み書きし、その内容と書き込まれたバイトを表示する単純なプログラムです。
実行すると、テキストを入力するまではすべて問題ないようです。親の印刷メッセージは正常に表示されますが、子の印刷メッセージは表示されません.どこでも特殊文字。
プログラムがどのように動作するかについての実行可能ファイルは次のとおりです。Linux : http://www.mediafire.com/?6806v24q6lz7dpc
そして、これまでの私のコード:
#include<stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[]) {
char FifoName[] = "fifoDan";
int fd;
pid_t retval;
int size_read;
char buff[80];
int size_written;
mknod(FifoName, S_IFIFO | 0666, 0);
// Check if its not equal to zero (ie: child process = 0)
if (retval = fork ()) {
printf ("Parent: Waiting for writers \n");
if(fd = open(FifoName, O_RDONLY) == -1) {
perror( "Could not read the FIFO" );
return EXIT_FAILURE;
}
printf ("Parent: Received a writer \n");
do {
int strsize;
size_read = read(fd, buff, sizeof(buff));
printf("Parent: read %d bytes: %s \n", size_read, buff);
fflush(stdout);
strsize = strlen(buff);
// put a '\0' at the end of the data
buff[strsize] = '\0';
} while(size_read > 0);
close(fd);
waitpid(retval, NULL, NULL);
if(unlink(FifoName) != -1) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
} else {
printf ("Child pid %d waiting for readers \n", getpid ());
fflush(stdout);
if(fd = open(FifoName, O_WRONLY) == -1) {
perror( "Could not read the FIFO" );
return EXIT_FAILURE;
}
printf ("Child: Got a reader, enter some stuff:\n");
fflush(stdout);
while(fgets(buff, 80, stdin) != NULL) {
int strsize;
strsize = strlen(buff);
if(strsize < 80) {
buff[strsize] = '\0';
}
size_written = write(fd, buff, sizeof(buff));
printf ("Child: wrote %d bytes \n", size_written);
fflush(stdout);
}
close(fd);
}
}