3

I created a random integer generator program. It takes in two arguments, a max number and a min number, and spits out a random integer within that range including both ends.

I am creating simulation programs in which I need random integer numbers and I want to be able to call the randomizer program and pass the max and mins I need for the simulation program to it and then return the random number to the simulation.

I just do not know and can not find the code I would need to write in the simulation to bring up the randomizer AND pass it the max and min values.

Thank you!

chriszumberge
  • 844
  • 2
  • 18
  • 33

2 Answers2

2

For your specific question, you should consider using popen(). Make sure to call pclose() after your are finished reading in your result.

FILE *input = popen("program -and args", "r");
if (input) {
  // read the input
  pclose(input);
} else {
  perror("popen");
  // handle error
}

If the program is reading its arguments from standard input, and then outputting the result to its standard output, you will need to create a bidirectional version of popen. Assuming you have a POSIX compliant OS, socketpair could be used to create your bidirectional channel (alternatively, you could make two calls to pipe). Then you would implement the functionality using fork and then one of the exec variants. This is discussed here.

But, as suggested by others, you should really just incorporate the functionality of your random number generator into your program as a function.

Community
  • 1
  • 1
jxh
  • 69,070
  • 8
  • 110
  • 193
1

The best way would be to create a library from your random generator and link against it. Otherwise, you can look up the execv() function.

Attila
  • 28,265
  • 3
  • 46
  • 55