简体   繁体   English

为什么带有 execlp 的 while 循环在一次迭代后退出循环?

[英]Why while loop with execlp is exiting the loop after one iteration?

I am trying to run an execlp() command inside a while loop.我正在尝试在 while 循环中运行 execlp() 命令。 The idea is it will take input from the user and depending on that it will execute the bash command (in this case, ls -la ).这个想法是它将接受用户的输入,并根据它执行 bash 命令(在本例中为ls -la )。

In the while loop, if I get 'c', I will create a child and want this child to execute execlp and then exit the child process.在while循环中,如果我得到'c',我将创建一个孩子并希望这个孩子执行execlp然后退出子进程。 The parent will wait until child exits then for safety I have used kill(PID, SIGKILL) to kill the child process.父进程将等到子进程退出,然后为了安全起见,我使用 kill(PID, SIGKILL) 杀死子进程。 I thought it should go back to the loop as exec is executed by the child, not the parent.我认为它应该回到循环,因为 exec 是由孩子而不是父母执行的。 I need the parent to be alive.我需要父母还活着。 What is the mistake here and how can I achieve my goal.这里的错误是什么,我该如何实现我的目标。 Below is the code:下面是代码:

pid_t child_pid;
int counter = 0;

int main()
{
   char c;

   while(1)
   {
      printf("enter choice: ");
      scanf(" %c", &c);
      // printf("\nyour choice was: %c\n", c);

      if (c == 'c')
      {
         int id = fork();
         if (id == 0){
            child_pid = getpid();
            printf("\ncreated child process at PID: %d\n", child_pid);
            execlp("ls", "ls",  "-la", (char *)0);
            // exit(0);
            }
         else{
            wait(NULL);
            kill(child_pid, SIGKILL);
            printf("\nkilled child\n");
            counter +=1;
         }
      }
      
      else if (c == 'e')
      {
         exit (0);
      }
    }

   return 0;
}

child_pid is assigned only in the child. child_pid仅在孩子中分配。 In the parent process, it is 0 (an initialized global), and kill kills the entire process group, including the parent.在父进程中,它是0(一个初始化的全局),并且kill杀死整个进程组,包括父进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM