How to provide Shell Escape from a C program?

Michael Davidson md at sco.COM
Thu Nov 22 08:31:08 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);
>		...

Well, I don't know exactly what is going wrong, but I have a few comments ...

First, why not just use "system()"?
There *are* sometimes good reasons for NOT using system(), but I don't
see any evidence in your code that you are trying to do anything clever
that wouldn't work just fine with system().

One comment on the code itself - do you *really* intend that the
parent process should be the one that exec's the shell?

Something like this would be more appropriate:

		if ((pid = fork()) == 0) {	/* child */
			execv("/bin/sh", args);
			perror("execv");
			_exit(1);
		} else if (pid > 0) {		/* parent */
			int	(*sigint)();
			int	r;

			sigint = signal(SIGINT, SIG_IGN);

			while ((r = wait(&status)) != -1)
				if (r == pid)
					break;

			signal(SIGINT, sigint);
		} else
			perror("fork");



More information about the Comp.unix.programmer mailing list