Re: Redirection issue



In article <1156959022.965599.76790@xxxxxxxxxxxxxxxxxxxxxxxxxxx>,
"souissipro" <souissipro@xxxxxxxx> wrote:

int
redir_cmd(char *argv[],char *in, char *out)

You don't seem to handle the case where only on direction is being
redirected. Perhaps you should allow a null point to be passed for the
ones that aren't being redirected, and check for this below before
calling open() and dup2().

This would also allow you to avoid having separate simple_cmd() and
redir_cmd() functions -- a simple command is just what you get if both
in and out are null, because it won't redirect anything.

{
int i;
int pid, status;
int fd1, fd2;
int dummy;

if (strcmp(argv[0],"exit")==0)
return do_exit(argv);
for(i=0;argv[i]!=NULL;i++)
printf("argv[%i]=\"%s\";\n",i,argv[i]);

if (strcmp(argv[0],"cd")==0)
{
return chdir(*argv);
}

if (fork() == 0) {
fd1 = open(in, O_RDONLY);
if (fd1 < 0) {
perror("can't open file : in");
exit(1);
}

if (dup2(fd1, out) != 0) {

This should be:

if (dup2(fd1, STDIN_FILENO) != 0) {

perror("catf1f2: dup2(in, 0)");
exit(1);
}
close(fd1);

fd2 = open(out, O_WRONLY | O_TRUNC | O_CREAT, 0644);
if (fd2 < 0) {
perror("catinout: out");
exit(2);
}
/*
if (dup2(fd2, 1) != 1) {

It's preferable to use STDOUT_FILENO instead of hard-coding 1.

perror("catf1f2: dup2(out, 1)");
exit(1);
}
*/
close(fd2);

execvp(*argv, argv);
perror(*argv);
exit(1);

}

/*
* parent executes wait.
*/
else {
wait(&dummy);
}

}

--
Barry Margolin, barmar@xxxxxxxxxxxx
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
.



Relevant Pages