Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a different program and passing it arguments

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!

like image 471
chriszumberge Avatar asked Dec 28 '25 21:12

chriszumberge


1 Answers

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.

like image 156
jxh Avatar answered Dec 31 '25 11:12

jxh