随机数 July 27, 2020

文件流真随机产生

Words count 6.8k Reading time 6 mins. Read count 0

学习一下文件流产生随机数的操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
int main()
{
const char *fifo_name = "/dev/urandom";
int pipe_fd = -1;
int data_fd = -1;
int res = 0;
int open_mode = O_RDONLY;
char buffer[PIPE_BUF+1];
int bytes_read = 0;
int bytes_write = 0;
memset(buffer,0,sizeof(buffer));
if(access(fifo_name,F_OK)==-1)
{
printf("Wrong!");
exit(0);
}
printf("PIPE_BUF_SIZE--->%d\n",PIPE_BUF);
printf("Process %d opening FIFO O_RDONLY\n",getpid());
pipe_fd = open(fifo_name,open_mode);
data_fd = open("data_fifo.txt",O_WRONLY|O_CREAT,0777);
printf("Process %d result %d\n",getpid(),pipe_fd);
printf("Process %d result %d\n",getpid(),data_fd);
if(pipe_fd!=-1)
{
res = read(pipe_fd,buffer,0x1000);
printf("read_size how--->%d\n",res);
bytes_write = write(data_fd,buffer,res);
bytes_read += res;
close(pipe_fd);
close(data_fd);
}
else
{
exit(EXIT_FAILURE);
}
printf("Process %d finished,%d bytes read\n",getpid(),bytes_read);
exit(EXIT_SUCCESS);
}
//随机数生成的方法学习
0%