我遇到了問題。試圖寫一個簡單的程序,其中分叉一次FIFO與/ dev/urandom
父進程從/ dev/urandom發送子字節,子進程將它們輸出到屏幕(15行,每行十六進制)。問題是:當我第一次打開編譯PROGRAMM輸出的樣子:
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 ... B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
(並不總是 「B0」,但肯定同一個字節) 當我運行同一程序(不重新編譯)再次輸出似乎是好的...任何想法?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
int main(int argc, char *argv[])
{
char bufforek[256];
printf("P1: READING /dev/urandom\n");
FILE *file_ptr = fopen("/dev/urandom", "r");
int file=open("FIFO",O_RDWR);
mkfifo("FIFO",0666);
char pomoc;
int hexa;
int i=1;
if(fork()==0)
{
char bufforek1[256];
while(read(file,bufforek1,sizeof(bufforek1)))
{
pomoc = *bufforek1;
// printf("%hhX ", pom);
hexa = (int)pomoc;
pomoc = *bufforek1;
printf("%hhX ", pomoc);
if(i==15)
{
printf("\n");
i=1;
}
else i++;
// write(pipe_table[1],bufforek,sizeof(bufforek));
}
return 0;
}
while ((fgets(bufforek, sizeof(bufforek), file_ptr))!=NULL) write(file, bufforek, sizeof(bufforek));
unlink("FIFO");
return 0;
}
幾個問題......爲什麼在打開它後創建fifo'mkfifo()'?而且你沒有檢查從每個fds讀取的字節數量...... – rodrigo