Calling compiled C program with Perl program

 
Thread Tools Search this Thread
Homework and Emergencies Homework & Coursework Questions Calling compiled C program with Perl program
# 1  
Old 02-20-2011
Calling compiled C program with Perl program

Long story short: I'm working inside of a Unix SSH under a bash shell. I have to code a C program that generates a random number. Then I have to call the compiled C program with a Perl program to run the C program 20 times and put all the generated random #s into a text file, then print that text file... then average the numbers in the text file and print the average.

I'm not entirely sure I'm doing this correctly (This is my first Perl program!) so if there are additional mistakes that anyone sees that will trip me up after I get this problem fixed, I'd more than welcome the feedback.

The error I'm getting with the command 'perl -w myperl':
Quote:
Can't exec "myprog": No such file or directory at myperl line 15.
The error I get with the command 'perl -d myperl':
Quote:
Can't locate perl5db.pl in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.0 /usr/local/share/perl/5.10.0 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .).
BEGIN failed--compilation aborted.
When I try to just type 'perl myperl', I get a 0 printed to the screen and nothing is in datafile.txt.

My C Program (called 'myproc.c', when compiled is 'myprog'):
Code:
#include <stdlib.h>
#define RAND_MAX      10

// function prototypes
void initrand(void);
int randint(int max);

// main function
int main(void)
{
        int randomNumber;
        int max = 10;

        initrand(); // generate the seed
        randomNumber = randint(max); // get the random number
        return randomNumber;
}

// this function seeds the random number generator
void initrand()
{
        srand((unsigned)(time(0)));
}

// this function generates a psuedo-random integer between 0 and max
int randint(int max)
{
        return (max*rand()/(RAND_MAX+1));
}

My Perl program (called 'myperl'):
Code:
# assign file handler for myprog
$outfile = 'datafile.txt';      # name file we're printing output to
open(INFO, $outfile);           # open file for output

for ($i = 0; $i < 20; $i++)     # run myprog 20 times
{
        $randNum = system(`myprog`);    # Get data from the C program
        print INFO $randNum;            # print collected data to $outfile
        print INFO '/n';                # print newline to $outfile
}

# assign input file handler
$infile = 'datafile.txt';       # name file to open for input
open(INFO, $infile);            # open file for input
@rands = <INFO>;                # put all the data from file into an array
print @rands;                   # print the array to get the contents of file

$j = 1;         # counter for averaging
$sum = 0;       # keeps up with final sum
foreach $number (@rands)        # loop through data to get the average
{
        $sum = $sum + $number;
        $j++;
}

$average = $sum / $j;   # calculate average
print "$average\n";     # print new average to the screen


School info: Arkansas State Univerity, Jonesboro, AR, Dr. Hai Jiang, CS 4-5223

---------- Post updated 02-20-11 at 12:35 PM ---------- Previous update was 02-19-11 at 06:03 PM ----------

I actually got this figured out with the help of a friend, so here's that answer if it helps anyone:

FOR THE PERL PART
When opening files for input and output in Perl, do it like this:
output-
Code:
open(INFO, '>' . $outfile);

input-
Code:
open(INFO, '<' . $infile);

To run the C program within your perl program:
Code:
$randNum = system(`./myproc`);    # Get data from the C program

FOR THE C PART
I had a problem within my initrand function which was causing all the output numbers to be the same. This is caused by the fact that the srand() function for seeding is by the second, which doesn't work when trying to run a program multiple times per second. This is a problem I'm actually still trying to work on a little, but that's a good first step towards solving your own problem.

I was trying to REdefine RAND_MAX, so that was renamed to RANDINT_MAX.

When casting an int, use parentheses:
return (int) (/*stuff*/);

Last edited by jdkirby; 02-20-2011 at 05:16 PM..
# 2  
Old 02-21-2011
  1. RAND_MAX does not work that way. RAND_MAX is something the compiler tells you -- the highest possible number the random number generator will ever give you. Usually, to generate numbers between 0-9, you'd do (rand()%10), and for numbers 1-10, (rand()%10)+1.
  2. This isn't DOS, you can't just run programs that happen to be in the current directory and expect them to be found. You have to tell it it's in the current directory by telling it ./myprog , not just myprog
  3. There's no point running system() on things you put in backticks. Do one, or the other: $code=system("./myprog"); $stuff=`./myprog`;
  4. system() doesn't return the program's text, it returns the program's return code (usually zero). If you want it's output, that's what backticks are for. $stuff=`./myprogram`;
  5. Perl almost certainly has the ability to generate random numbers without calling a C program. In fact perl has a rand() too (try perldoc -f rand) which seems more convenient. You can just do $stuff=int(rand(10))+1; to get numbers 1-10. Modern versions of perl also call srand by themselves when run, so you get a different random starting point every time without any effort on your part.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Perl program get a response before the program quits

I created a program, so a kid can practice there math on it. It dispenses varies math problems and the kid must input an answer. I also want it to grade the work they have done, but I can't find the best place for it to print out the grade. I have: if ( $response =~ m/^/ ) { $user_wants_to_quit... (1 Reply)
Discussion started by: germany1517
1 Replies

2. Red Hat

Run program compiled in Ubuntu in centos

Will a program compiled in ubuntu 14.04 execute in Centos 7? That is to say a tarball or zip is downloaded from github and extracted, compiled, and make is all done in ubuntu 14.04, can I mv the program from ubuntu 14.04 to Centos 7, add it to path in Centos 7. And run it? Thank you :) (3 Replies)
Discussion started by: cmccabe
3 Replies

3. Programming

Using ANSI color codes in gcc compiled program

I have put some yellow color codes and works well. I call the funstion using print_usage(stderr, 0); I would like to know if there is any way, to store the ansi color codes in variables and then call them inside fprintf. Or have a format followed by the strings I want to output. ... (5 Replies)
Discussion started by: kristinu
5 Replies

4. Solaris

Issue in pro*C program compiled in solaris 10

Hi, We upgraded our servers from solaris 9 to 10. We recompiled all the Pro*C programs with the new oracle version as well. Oracle is 11g. We are facing core dump with the below error for certain executions. But when we are placing new statements between the error fucntion we get junk values to... (1 Reply)
Discussion started by: saroopkris85
1 Replies

5. UNIX for Dummies Questions & Answers

Making a program compiled on Unix (HPUX) work on Linux

I am trying to make an application which works on unix to work on linux. I already tried copying the binary files and start it up but I am getting an error stating "Cannot execute binary file". Then I tried to recompile but i am getting an error whenever I tried to recompile. I am getting the... (1 Reply)
Discussion started by: khestoi
1 Replies

6. Shell Programming and Scripting

Calling perl script in shell program

How to call a perl script in shell program / shell scripting. PLS HELP ME (2 Replies)
Discussion started by: hravisankar
2 Replies

7. UNIX for Dummies Questions & Answers

Calling a c program using perl script

On bash I run precompiled c Program as follows: ./create_cust 1 10000 US S > us_cust.csv create_cust is a c program and requires 4 parameters. I am redirecting the output of this program to csv file I need to run this same program in perl I am aware of exec command though not... (7 Replies)
Discussion started by: gkbond
7 Replies

8. Shell Programming and Scripting

Problem with `cat` the compiled output of C program in unix

Hello All, I have coded a C program which looks something like below... (program name: test.c) #include<stdio.h> main() { int dist,dm,dcm; printf(" Enter the distance between 2 cities in KM : "); scanf("%d",&dist); dm=dist*1000; dcm=dist*10; printf("Distance between 2 cities in... (6 Replies)
Discussion started by: smarty86
6 Replies

9. Programming

How to use a .exe with a compiled program.

I am confused about how to use a .exe file in unix along with a compiled C++ program. I've been using emacs and I compiled with g++, but I have no idea how that relates to use with a .exe. (1 Reply)
Discussion started by: adamsy
1 Replies

10. Programming

Running a compiled Program

Just getting into the Unix command line programming and am unable to run any program I write. I am using a Makefile and the source is compiling but when I enter the name of the output file I get back: bash: lab01exe.out: command not found I'm sure I am just dooing something simple... (2 Replies)
Discussion started by: Krebsbac
2 Replies
Login or Register to Ask a Question