0

I have some problem with execvp in my code, I want to write a simple terminal which save the result of command in log file, the problem is that when I use "> a.log" which should bring the result to the output, it is not responding and goes to error!

int lsh_launch(char **args)
{
pid_t pid;
int status;
int i = 0;
while (args[i] != NULL)
{
    printf("%s\n", args[i]);
    i++;
}
args[i] = ">";
args[i + 1] = "a.log";
pid = fork();
if (pid == 0)
{
    printf("child proc\n");
    // Child process
    if (execvp(args[0], args) == -1)
    {
    perror("lsh");
    }
    if (execvp(args[0], args)  == -1)
    {
    perror("lsh");
    }
    exit(EXIT_FAILURE);
}
else if (pid < 0)
{
    // Error forking
    perror("lsh");
}
else
{
    // Parent process
    do {
    waitpid(pid, &status, WUNTRACED);
    } while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}

When I change args with other value (for example -v to see the version) it works, and it seems the problem is with exporting to output! the result when I do ls and > a.log with program is:

-  ls: cannot access >: No such file or directory
-  ls: cannot access a.log: No such file or directory

2 Answers 2

3

Redirections are not obtained this way. > (or similar) is a syntax to make redirection in a shell. The shell interprets the command line and make redirections before execing the command, this way :

pid = fork();
switch(pid) {
case 0:
  d = open("myfile",O_WRONLY);
  dup2(d,STDOUT_FILENO); // redirect *stdout* to open file d by duplicating it
  close(d); // now unused d (d is a duplicate of *stdout*
  exec**(...); // now mutate to a new code which inherits open file descriptors
  exit(1);
  break;
case -1: // error case of fork
  break;
default:
  wait(NULL); // or whatever you want, don't wait for *background style*
  break;
}
1
  • Nice ... So much better to use a switch! but also see my answer, there is yet a more fundamental problem. Although your answer actually answers the actual question. Nov 14, 2015 at 14:48
0

Assuming args is the argv passed to the main() function1:

Your program invokes Undefined Behavior

while (args[i] != NULL)
{
    printf("%s\n", args[i]);
    i++;
}

At the end of this loop, i has a value beyond the bounds of the args array. Thus

args[i] = ">";
args[i + 1] = "a.log";

tries to write there at the forbidden location, invoking undefined behavior.


1It's not clear because apparently some code is missing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.