wait() & 在父循环中 linux

wait() & in partent loop linux

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

void main(){
   int x,y,status, i;
   int cnt = 0;
   int flag = 0;
   char buf[50];
   char str[50];
   char * argv[10];
   char * ptr;


   for(i=0; i<10; i++){
    printf("$");
    gets(buf);
    strcpy(str, buf);

    ptr = strtok(buf, " ");

    while(ptr != NULL){
      argv[cnt] = ptr;
      cnt++;
      ptr = strtok(NULL," ");
    }



    if(!strcmp(argv[cnt-1], "&")) {
      argv[cnt-1] = 0;
      flag = 1;
    }
    else {
        argv[cnt] = 0;
    }



    if(!strcmp(argv[0],"exit")) exit(0);

    x=fork();

    if (x==0){
        sleep(1);
        printf("I am child to execute %s\n", str);
        y=execve(argv[0], argv, 0);

        if (y<0){
           perror("exec failed");
           exit(1);
        }

    }
    else {
      if(flag == 0) { 
          wait(&status); 
      }
    }


    flag = 0;
    cnt = 0;
   }
}

我想用'&'执行后台

像真的一样linuxshell

所以我分了

   else {
      if(flag == 0) { 
          wait(&status); 
      }
    }

像这样

所以效果很好

如果我输入 /bin/ls(没有 &) 提示$放在/bin/ls

之后

如果我输入 /bin/ls &(带 &) 然后提示$放在/bin/ls

之前

但重写 /bin/ls(不带 &),就像我第一次输入时一样 然后提示 $ 放在 /bin/ls

之前

为什么?

===============

$/bin/ls
I am child to execute /bin/ls
ch f1 f2 shell shell.c t t.c test test.c testfile

$/bin/ls &
$I am child to execute /bin/ls &
ch f1 f2 ch f1 f2 shell shell.c t t.c test test.c testfile

$/bin/ls
$I am child to execute /bin/ls
ch f1 f2 shell shell.c t t.c test test.c testfile

================
Is it right?

我会说“$”行为是预期的。

我什至不知道这段代码是如何编译的。您不能使用 void main(){(至少在使用 gcc 时)。有效形式为 int main() {。此外,您可以大大简化代码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main() { /*Changed void main()*/
   int x, y, status, i, cnt=0, flag=0; /*Squashed declarations*/
   char buf[50]; /*removed str*/
   char * argv[10], * ptr;
   for(i=0; i<10; i++){
      putchar('$'); /*printf() is overkill. Also, watch out for this!*/
      fgets(buf, 49, stdin); /*49 (null terminator), gets --> fgets*/
      /*strcpy(str, buf); <-- why?*/
      ptr = strtok(buf, " ");
      while(ptr != NULL) {
          argv[cnt++] = ptr;
          ptr = strtok(NULL," ");
      }
      if(!strcmp(argv[cnt-1], "&")) {
          argv[cnt-1] = 0;
          flag = 1;
      } else {
          argv[cnt] = 0;
      }
      if(!strcmp(argv[0],"exit"))
          return 0;
      x=fork();
      if (!x) {
          sleep(1);
          y=execve(argv[0], argv, 0);

          if (y<0) {
              perror("execve failed");
              return 1;
          }

      } else {
          if(!flag) { 
              wait(&status); 
          }
      }
      flag = 0;
      cnt = 0;
   }
}

您正在创建子项,并且在每种情况下都回显“$” - 这使得“$”出现。

之后,fork(),即使您正在执行进程,“$”也会再次显示。