This code works, redirecting to file.out
:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *redirect[] = { ">", "file.out" };
char *command[] = { "/bin/ls", "-l", 0 };
if (!strcmp(redirect[0], ">"))
{
if ((fd = open(redirect[1], O_WRONLY | O_CREAT, 0644)) != -1)
{
fprintf(stderr, "Dupping stdout to %s\n", redirect[1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (command[0][0] == '/')
{
execv(command[0], command);
fprintf(stderr, "ERROR: command %s does not exist at path specified\n", command[0]);
return(1);
}
else
{
fprintf(stderr, "ERROR: not handling relative names like %s\n", command[0]);
return(1);
}
return 0;
}
This code works too, not redirecting to file:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *redirect[] = { "<", "file.in" };
char *command[] = { "/bin/ls", "-l", 0 };
if (!strcmp(redirect[0], ">"))
{
if ((fd = open(redirect[1], O_WRONLY | O_CREAT, 0644)) != -1)
{
fprintf(stderr, "Dupping stdout to %s\n", redirect[1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (command[0][0] == '/')
{
execv(command[0], command);
fprintf(stderr, "ERROR: command %s does not exist at path specified\n", command[0]);
return(1);
}
else
{
fprintf(stderr, "ERROR: not handling relative names like %s\n", command[0]);
return(1);
}
return 0;
}
Note that it sets up the command
array and uses execv(command[0], command);
— this is the recommended way of doing business. Your code appears to have a variable commands
with presumably the arguments to the program; you also appear to have a variable path
with presumably the path name of the program. Since we can't see what's in those, it is hard to know what they contain and where there might be problems. Note the explicit null pointer (0
) at the end of the command
array. That is crucial. Note too that the error messages identify what was failing. There are few things more frustrating than a program that says "it went wrong" without identifying what 'it' is.