Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

using a string variable in a system call in C code

 
SOLVED
Go to solution
Highlighted
Boyd Kodama
Frequent Advisor

using a string variable in a system call in C code

I am trying to figure out to make a system call in C code to execute a script
that resides in each user's home directory. I pass the username and userid
as arguments. Here's a sample of the latest version of the code:

#include
#include
#include
#include
void main (argc, argv)
int argc;
char **argv;
{
struct passwd *user;
setuid(atoi(argv[2]));
user=getpwnam(argv[1]);
system("%s/test_script", user->pw_dir);
setuid(0);
}

Executing it gives the following:

sh: %s/test_script: not found.

Replacing the 'system' with 'printf' and executing it gives the following:

/user1/bkodama/test_script

as desired.

The 'system' call does not seem to recognize the string variable.
Any ideas??? Thanks,
Without Mondays, there weren't be any Fridays
2 REPLIES 2
Highlighted
Boyd Kodama
Frequent Advisor

Re: using a string variable in a system call in C code

Just figured it out.

Added:

char upath[120];

Revised:

system(upath,"%s/.dt/sessions/sessionexit", user->pw_dir);

to

sprintf(upath,"%s/.dt/sessions/sessionexit", user->pw_dir);
system(upath);

And it worked.
Without Mondays, there weren't be any Fridays
Highlighted
RikTytgat
Honored Contributor
Solution

Re: using a string variable in a system call in C code

Hi,

You are right, but I have some small remarks.

You need two arguments to your program, the username and uid. The uid us present in the passwd struct you obtain by using getpwnam call. The code I included shows how to do this.

Also, be sure to test the returned value of the calls you use. In your program, the setuid call could easily not work (if executed by another user), but the program would continue and try to execcute the script.

Bye,
Rik