How to provide Shell Escape from a C program?

Craig Schmackpfeffer cs at cci632.UUCP
Wed Nov 21 01:55:14 AEST 1990


In article <349 at clbull.cl.bull.fr> rudrak at saphir.cl.bull.fr (Rudrakshala Purushotham) writes:
>I want to provide shell escape feature from a C program. But I am having 
>some problems with the following code:
>	shell_escape (command);
			      ^
			      |
>	char *command;
>	{
>		char *args [MAX_ARGS];
>
>		args [0] = "/bin/sh";
>		args [1] = "-c";
>
>		for (i = 2; i < MAX_ARGS && (s = strtok (command, " \t")); i++)
>			args [i] = strsave (s);
>		
>		args [i] = NULL;
>
>		if (fork () > 0)	{
			    ^^^
			    |||
>			execv ("/bin/sh", args);
>			perror ("execv");
>			_exit (1);
>		}
>
>		wait (&status);
>
>I am using C shell and System V. I tried `/bin/ls -l -R' as input to
>shell_escape (), my .login file gets executed here and /bin/ls is executed
>(without -l -R) options. 

>-- Purushotham 


My first question would be "why re-invent the wheel?".  You could use the
system() call and not worry about any of the parsing and fork/exec'ing.
In fact, it your function cannot work properly because you are having the
parent process do the exec instead of the child.  

You only get the output of ls (with no -l -R) because the shell wants to 
parse the command itself.

Here's how the function could look:

	shell_escape (command)
	char *command;
	{
		char *args [MAX_ARGS];

		args [0] = "/bin/sh";
		args [1] = "-c";
		args [2] = command;
		args [3] = NULL;

		switch (fork())  {
		    case 0:		/* child */
				execv("/bin/sh", args);
		    case -1:		/* fork error or exec fallthrough */
				perror("fork/exec");
				_exit(1);
		    default:		/* parent */
				wait(&status);
		}
	}

		--  or better yet  --

	system(command);

Craig

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Me:          Craig Schmackpfeffer   (another damn yankee)
Disclaimer:  Disclaim'er? I don't even know her!
Address:     ccird1!cs at cci632.UUCP             			Go Bills!
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =



More information about the Comp.unix.programmer mailing list