Link to home
Start Free TrialLog in
Avatar of jma2000
jma2000

asked on

Passing int in execl

I need to pass an int (30) to be used in program called by execl.

for example:

execl("progb", "30", NULL);

main in progb looks like this:

int main(int argc, char *argv[])

I thought I could do the following but it doesn't work:  

int counter = atoi(argv[1]);
Avatar of Axter
Axter
Flag of United States of America image

>>I thought I could do the following but it doesn't work:  


That should have work.
How do you know it's not working?
Try the following for your execl call.

execl("progb", "progb", "30", NULL);
Avatar of grg99
grg99

Execl expects all the parameters to be text strings, so you don't have to convert the argv[] string at all.
Just pass argv[1].

Avatar of jma2000

ASKER

I need the parameter to be an int to use as a counter in called program.
Every program gets an argv[] array.  It's always an array of zero-terminated strings.

If the program needs to extract an integer from it, the program does a:

int TheIntParam = atoi( argv[1] );

... it has nothing to do with the execl end of it.

Oh, I see your problem.  Well, two problems.

In your called program you should really check argc before peeking at argv[1].  The reason why later.

int number;

if( argc < 2 )   number = 99999;  // whatever you want the default to be if no param specified
else
    number = atoi( argv[1] );

In general you should NEVER assume that input is always there to be grabbed.  Always check before peeking.

----

the reason this is important in this case, and would have avoided you having to call in us big guns, is that the second parameter to execl is a list of the arguments to be passed to the program INCLUDING THE [0] argument, the program name.

So you need to change "30" to "somename.exe 30".

Dont' ask me why you're allowed to execute one file and then pass it off as a different name.

.
jma2000,
Did you try my previously posted recommended fix:

execl("progb", "progb", "30", NULL);


That is the answer to yoru question.  Notice that "progb" is in there twice...

Adding validation checks is good, but will not fix the code.
The calling function needs the above change to fix the code.
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jma2000

ASKER

Yes it worked.  Thanks.