For
dup2
you can have a look here:
dup2(2) - Linux man page[
^]
For the code, start with an outer loop where you split the input string at the pipe character. Then create a function that takes care of the execution of the each command.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
size_t TrimWhiteSpace(char *out, size_t len, const char *str);
void ExecuteCommand(const char* command);
int main()
{
char input[80] = "ls / tmp | wc - l";
const char sep[2] = "|";
char *token = NULL;
char* command = NULL;
token = strtok(input, sep);
while (token != NULL)
{
command = (char*)calloc(strlen(token) + 1, sizeof(char));
TrimWhiteSpace(command, strlen(token) + 1, token);
printf("%s\n", command);
ExecuteCommand(command);
token = strtok(NULL, sep);
}
return 0;
}
size_t TrimWhiteSpace(char *out, size_t len, const char *str)
{
if (len == 0)
return 0;
const char *end;
size_t out_size;
while (isspace(*str))
str++;
if (*str == 0) {
*out = 0;
return 1;
}
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
end++;
out_size = (end - str) < len - 1 ? (end - str) : len - 1;
memcpy(out, str, out_size);
out[out_size] = 0;
return out_size;
}
void ExecuteCommand(const char* command)
{
}
(The method TrimWhiteSpace, I found at StackOverflow:
How do I trim leading/trailing whitespace in a standard way?[
^])
This link might be interesting as well:
Execute a Program: the execvp() System Call[
^]