Lab overview
Lab 01
Lab 02
Lab 03
Lab 04
Lab 05
Lab 06
Lab 07
Lab 08
Lab 09
Lab 10
Lab 11
Lab 12
Lab 13
Review

[Course home page]

CSC 209 lab 09 exercises, week of 12 July 2022

Executing a command by running sh −c

If you have an arbitrary command in a string (often this would have been typed by a user), you can use the shell to parse and execute it. The shell has a −c option for precisely this purpose.

The −c option expects an argument in a single argv member which is the entire command to be parsed and executed. Note that you don't have to remove any trailing \n from the line, because that doesn't affect the semantics of the shell command!

Sample call shown in class:

	execl("/bin/sh", "sh", "-c", "ls | tr -ef", (char *)NULL);
	perror("/bin/sh");
	exit(1);

Of course you can use a string variable instead of the "ls | tr −ef" above.