我正在尝试使用C语言在Linux中创建自己的shell。 好吧,我成功地做了一些基本命令和I / O重定向"但当我试图用#&"来制作"后台执行程序时我失败了。它没有在背景上工作。例如,预期是:
> sleep 5 &
> cat file.txt
will print the content of file.txt
> [24617] retval: 0
但正在发生的事情是:
> sleep 5 &
> [24617] retval: 0
> cat file.txt
will print the content of file.txt
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>
#include <termios.h>
#define MAX_WORD 10
#define MAX_CHAR 100
int input_redirection_flag;
int output_redirection_flag;
int background;
char* input_file=NULL;
char* output_file=NULL;
void remove_endOfLine(char line[]){
int i=0;
while(line[i]!='\n')
i++;
line[i]='\0';
}
void read_line(char line[]){
char* ret=fgets(line,MAX_CHAR,stdin);
remove_endOfLine(line);
if(strcmp(line,"quit")==0 || ret==NULL)
exit(0);
}
int process_line(char* temp[],char line[]){
int i=0;
temp[i]=strtok(line," ");
while(temp[i]!=NULL){
temp[++i]=strtok(NULL," ");
}
return 1;
}
int redirection_background_checking(char* temp[]){
int i=0;
background=0;
while(temp[i] != NULL){
if(strcmp(temp[i],">")==0){
output_redirection_flag=1;
output_file=temp[i+1];
return i;
}
if(strcmp(temp[i],"<")==0){
input_redirection_flag=1;
input_file=temp[i+1];
return i;
}
if(strcmp(temp[i],"&")==0){
background=1;
temp[i]=NULL;
}
i++;
}
return i;
}
void check_line(char* temp[]){
int i=0;
int output_redirection_cnt=0;
int input_redirection_cnt=0;
if(temp[i]==NULL){
printf("NO COMMAND\n");
return ;
}
while(temp[i] !=NULL){
if(strcmp(temp[i],">")==0)
output_redirection_cnt++;
if(strcmp(temp[i],"<")==0)
input_redirection_cnt++;
i++;
}
if(output_redirection_cnt+input_redirection_cnt>1){
printf("you cannot use more than 1 signal.");
temp[0]=NULL;
}
}
int read_parse_line(char* args[],char line[]){
char* temp[MAX_WORD];
int pos;
int i=0;
read_line(line);
process_line(temp,line);
check_line(temp);
pos=redirection_background_checking(temp);
while(i<pos){
args[i]=temp[i];
i++;
}
args[i]=NULL;
i++;
}
int main()
{
char line[MAX_CHAR];
char* args[MAX_WORD];
char * tokens[MAX_WORD];
printf("> ");
fflush(stdout);
while(read_parse_line(args,line)){
pid_t pid=fork();
if(pid==0){
if(input_redirection_flag==1&&input_file!=NULL)
dup2(open(input_file,O_RDWR|O_CREAT,0777),0);
if(output_redirection_flag==1&&output_file!=NULL)
dup2(open(output_file,O_RDWR|O_CREAT,0777),1);
execvp(args[0],args);
}
else if(pid<0){
printf("failed Process");
}
else{
input_redirection_flag=0;
output_redirection_flag=0;
input_file=NULL;
output_file=NULL;
}
if (background == 0){
waitpid(pid,NULL,0);
}else{
printf("[%d] retval: %d\n",pid,0);
}
if(background == 1 && args[1]=="quit")
break;
printf("> ");
fflush(stdout);
}
return 0;
}