-2

EDIT I: Windows subsystem for Linux.


I bet I'm doing something wrong and/or really stupid.

// random_problems.c

#include <stdio.h>

main(){
  int rng;
  FILE * urnd = fopen("/dev/random", "r");
  read(urnd, &rng, 1);
  close(urnd);
  printf("%d\n", rng);
}

$ ./random_problems
32767
$ ./random_problems
32767
$ ./random_problems
32767

Same result every time.

And yes, I checked: /dev/random is changing. (Line breaks added)

[~] Connor >> head /dev/random -c 1
P
[~] Connor >> head /dev/random -c 1
m

I get the same problem with /dev/urandom.

I put the thing on loop with this little script:

echo "32767" > 32767; while [ $? -eq 0 ]; do ./random_problems > rng; diff -s rng 32767; done; rm rng 32767

(It even cleans up after itself!)


So, how stupid is this problem?

6
  • 1
    I bet the problem is really stupid. – SIGSTACKFAULT May 7 '17 at 18:00
  • 1
  • 1
    The first problem is that you aren't checking compilation errors or you're invoking your compiler in a mode where it compiles garbage without complaining. With GCC, use at least gcc -O -Wall. The second problem is that you aren't checking the return code from functions that can fail, such as fopen and read. – Gilles 'SO- stop being evil' May 7 '17 at 22:34
  • It's a short working example. I don't want to make it overcomplicated and confusing by doing all the error checking. – SIGSTACKFAULT May 8 '17 at 14:18
  • @Blacksilver this can't be migrated since you are blocked from asking on Stack Overflow. – terdon May 8 '17 at 14:24
3

You’re using read with a FILE pointer, when it expects a file descriptor:

int urnd = open("/dev/random", O_RDONLY);

You’ll need to add some headers, and you might as well read as many bytes as will fit into your int:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv){
  int rng;
  int urnd = open("/dev/random", O_RDONLY);
  read(urnd, &rng, sizeof(int));
  close(urnd);
  printf("%d\n", rng);
  return 0;
}

(You should also check for errors.)

1
  • Ty. I knew the problem was really stupid. – SIGSTACKFAULT May 7 '17 at 18:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.