Reputation: 119
Could someone explain to me why this gives the normal behavior (ls | cat)
int fd[2]; pipe(fd);
pid_t pid = fork();
if(pid > 0) {
close(fd[0]);
close(STDOUT_FILENO);
dup2(fd[1],STDOUT_FILENO);
execlp("ls","ls",NULL);
} else if (pid == 0) {
close(fd[1]);
close(STDIN_FILENO);
dup2(fd[0],STDIN_FILENO);
execlp("cat","cat",NULL);
} else {
error(1, errno, "forking error");
}
but when I change execlp to execvp suddenly nothing is output and exit status is 255? Code:
int fd[2]; pipe(fd);
pid_t pid = fork();
if(pid > 0) {
close(fd[0]);
close(STDOUT_FILENO);
dup2(fd[1],STDOUT_FILENO);
char **args = {"ls", NULL};
execvp("ls",args);
} else if (pid == 0) {
close(fd[1]);
close(STDIN_FILENO);
dup2(fd[0],STDIN_FILENO);
char **args = {"cat", NULL};
execvp("cat",args);
} else {
error(1, errno, "forking error");
}
I'd really like to use execvp because I'll be executing commands with variable length arg lists. Help would be much appreciated.
Upvotes: 0
Views: 1309
Reputation: 21507
char **args = {"ls", NULL};
should be char *args[] = {"ls", NULL};
, and the same for the second args
(for cat
).
(It's too late here, so I can't think of the reason for the first one to compile. At least it gives a warning).
Upvotes: 2