您好我正在编写一个用于输入输出重定向的shell脚本。代码如下
int parse(void)
{
char *p; /* pointer to current word */
char *msg; /* error message */
nwds = 0;
p = strtok(line," \t");
while (p != NULL) {
if (nwds == NWORDS) {
msg = "Error: too many words.\n";
write(2 ,msg, strlen(msg));
return 0;
}
if (strlen(p) >= MAXWORDLEN) {
msg = "Error: Word too long.\n";
write(2, msg ,strlen(msg));
return 0;
}
if(*p == '<') /* check if input symbol is present*/
isInput = true;
if(*p == '>') /* check if Output symbol is present*/
isOutput = true;
if(isInput) {
p = strtok(NULL," \t"); /* get pointer to next word, if any */
input = p;
}
if(isOutput) {
p = strtok(NULL," \t"); /* get pointer to next word, if any */
output = p;
}
words[nwds] = p; /* save pointer to the word */
nwds++; /* increase the word count */
p = strtok(NULL," \t"); /* get pointer to next word, if any */
}
return 1;
}
以上代码从输入获取命令并验证命令数和字长。它还验证输入和输出重定向字符,并将文件名存储在输入和输出字符指针
中int execute(void)
{
int i, j;
int status;
char *msg;
pid_t child_pid;
int in;
int out;
if (execok() == 0) { /* is it executable? */
status = fork(); /* yes; create a new process */
if (status == -1) { /* verify fork succeeded */
perror("fork");
exit(1);
}
if (status == 0) { /* in the child process... */
words[nwds] = NULL; /* mark end of argument array */
if(input != NULL && output != NULL)
{
in = open (input, O_RDONLY);
out = open (output, O_TRUNC | O_CREAT | O_WRONLY, 0666);
if ((in <= 0) || (out <= 0))
{
fprintf (stderr, "Couldn't open a file\n");
exit (errno);
}
dup2(in, 0);
dup2(out, 1);
close(in);
close out);
}
status = execve(path,words,environ); /* try to execute it */
perror("execve"); /* we only get here if */
_exit(0); /* execve failed... */
}
/*------------------------------------------------*/
/* The parent process (the shell) continues here. */
/*------------------------------------------------*/
child_pid = wait(&status); /* wait for process to end */
if (v_opt) { /* display status? */
char emsg[100];
if (WIFEXITED(status))
sprintf(emsg,"Child process %u exited with status %d.\n",
child_pid, WEXITSTATUS(status));
else
sprintf(emsg,"Child process %u did not exit normally.\n",
child_pid);
write(1,emsg,strlen(emsg));
}
} else {
/*----------------------------------------------------------*/
/* Command cannot be executed. Display appropriate message. */
/*----------------------------------------------------------*/
msg = "Error: '";
write(2,msg,strlen(msg));
write(2,words[0],strlen(words[0]));
msg = "' cannot be executed.\n";
write(2,msg,strlen(msg));
}
}
这是执行重定向的执行功能。
我是shell脚本的新手,我通过网络获得了一些知识,并编写了这个程序。该程序不重定向输入和输出。你能帮帮我吗