C 为什么我的shell在终止进程后打印不正确?

C 为什么我的shell在终止进程后打印不正确?,c,linux,shell,C,Linux,Shell,当“&”结束时,我正在进行后台处理。我认为它工作正常,但由于某种原因,在杀死一个进程后执行任何命令后,“Ben$”打印得很奇怪,我不明白为什么 这是它正在打印的内容: Ben$ ls Makefile shell2 shell2.c stableshell2.c Ben$ sleep 20 & Ben: started job 30892 Ben$ kill 30892 Ben$ ls Ben$ Makefile shell2 shell2.c stableshell2.c

当“&”结束时,我正在进行后台处理。我认为它工作正常,但由于某种原因,在杀死一个进程后执行任何命令后,“Ben$”打印得很奇怪,我不明白为什么

这是它正在打印的内容:

Ben$ ls
Makefile  shell2  shell2.c  stableshell2.c
Ben$ sleep 20 &
Ben: started job 30892
Ben$ kill 30892
Ben$ ls
Ben$ Makefile  shell2  shell2.c  stableshell2.c
ls
Ben$ Makefile  shell2  shell2.c  stableshell2.c
有什么想法吗

/*
  Shell 1
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdbool.h>

#define DELIMS " \t\r\n"
int main (int argc, char *argv[]) {
  while (1) {
      char line[100];
      char *temp;
      char *split[15];
      int pid;
      bool background=false;

        printf("Ben$ ");

    //if cmd-d, exit shell
     if(!fgets(line, sizeof(line), stdin)) {
      printf("\n");
      break;
   } 

      line[strlen(line)-1]='\0';
      temp=strtok(line," ");


      if (strcmp(temp, "exit") == 0) {
        break;
      }
      else if (strcmp(temp, "cd") == 0) {
        char *arg = strtok(0, DELIMS);

        if (!arg) {
          fprintf(stderr, "cd missing argument.\n");
        }
        else {
          chdir(arg);
        }

      } else {
      int i=0;
      while(temp != NULL) {
        split[i]=temp;
        temp=strtok(NULL," ");
        i++;
      }
      split[i] = NULL;
      if(strcmp(split[i-1], "&")==0) {
        // printf("should do in background");
        split[i-1]='\0';
        background=true;
      }

      char *args[i];
      int j;
      for(j=0; j < i; j++){
        args[j]=split[j];
      }


        pid=fork();

        if(pid==0) {
        if(background) {

                  fclose(stdin);
                  fopen("/dev/null","r");
        }
        execvp(args[0], args);
        printf("This should not happen\n");
      }
      else {
        if(!background) {
          // printf("Not in background\n");
             wait(&pid);
        }
        else {
           printf("Ben: started job %d\n",pid);
        }
     }
    }

  }
  return 0;
}
/*
外壳1
*/
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#定义DELIMS“\t\r\n”
int main(int argc,char*argv[]){
而(1){
字符行[100];
字符*温度;
字符*split[15];
int-pid;
布尔背景=假;
printf(“Ben$”);
//如果是cmd-d,则退出shell
如果(!fgets(线,尺寸(线),标准){
printf(“\n”);
打破
} 
行[strlen(行)-1]='\0';
温度=strtok(第“”行);
如果(strcmp(临时,“退出”)==0){
打破
}
否则如果(strcmp(温度,“cd”)==0){
char*arg=strtok(0,DELIMS);
如果(!arg){
fprintf(stderr,“cd缺少参数。\n”);
}
否则{
chdir(arg);
}
}否则{
int i=0;
while(temp!=NULL){
分割[i]=温度;
temp=strtok(空,“”);
i++;
}
split[i]=NULL;
如果(strcmp(拆分[i-1],“&”)==0){
//printf(“应在后台执行”);
拆分[i-1]='\0';
背景=真;
}
字符*args[i];
int j;
对于(j=0;j
这并不奇怪

您正在异步调用进程,因此可以在控制台中交错它们的输出