passing a string to exec

B

barncat

hi
here is a small snip of code that passes a char array to the excelp func. does anybody know when building the string with strcat(), exec fails? I dont really have an issue, just curious. thanks

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

char cmd[256];

/* for some reason, strcat wont work
strcat(cmd,"ls");

/* these work:
sprintf(cmd, "ls");
strcpy(cmd, "ls");
*/

printf("command: %s",cmd);
execlp(cmd, cmd, NULL);
}
 
B

Ben Bacarisse

barncat said:
... does anybody know when building the string with strcat(), exec
fails?
int main ( int argc, char *argv[] )
{

char cmd[256];

/* for some reason, strcat wont work
strcat(cmd,"ls");

strcat requires cmd to be a string -- i.e. to have a terminating null.
It's purpose is to add one string *after* whatever is in cmd, and you
don't know what that is, not having put anything there.

cmd[0] = 0;
strcat(cmd,"ls");

should work.
 
B

barncat

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

char cmd[256];
/* for some reason, strcat wont work
strcat(cmd,"ls");


strcat requires cmd to be a string -- i.e. to have a terminating null.

It's purpose is to add one string *after* whatever is in cmd, and you

don't know what that is, not having put anything there.



cmd[0] = 0;

strcat(cmd,"ls");



should work.



printf("command: %s",cmd);
execlp(cmd, cmd, NULL);

yep that works, i was confused because the man pages for strcat and strcpy are similar. now that i re read the man page for strcat(), your explanation makes sense. thank you!!
 
S

Szabolcs Nagy

barncat said:
printf("command: %s",cmd);
execlp(cmd, cmd, NULL);

note that this might invoke undefined behavior,
the last argument should have char* type,
NULL might not have pointer type at all
(assuming posix execlp)

in var arg functions the argument type must match
exactly the expectation of the callee (different
pointer types might have different representations
and type conversion cannot occure since there is
no type information available, in practice object
pointers usually have the same representations and
NULL is defined as ((void*)0) so it happens to work,
but c does not mandate it)

correctly

execlp(cmd,cmd,(char*)0);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top