Call execv
in a C program.
int status = execv("/bin/ls", (char *[]) { "ls", "-l", NULL } );
/* If execv returns, something happened. */
printf("Exec returns %d\n", status);
perror("Unknown command\n");
exit(1);
See complete listing below.
Compile and link with:
gcc -Wall -o testexec.c
If you have to parse the shell commands, consider strtok
, e.g.
// Dynamically size cmd[]
char delim[] = " ";
char *index = strtok(cmd, delim);
To support a pipeline, you will need to invoke the pipe()
call and use dup()
to copy descriptors. There is a nice example on StackOverflow. But the idea is to set up a pipeline and then redirect STDOUT
to the pipe's read descriptor. Then use exec
to start a second process and redirect STDIN
to the pipe's write descriptor. You can do this implicitly with dup
or explicitly with dup2
.