简体   繁体   English

如何终止子进程中的程序?

[英]How to terminate a program from a child process?

I am trying to terminate my program which takes a line that is full of commands from a file and then process each command using execvp 我试图终止我的程序,该程序从文件中提取一行包含命令的行,然后使用execvp处理每个命令

However,Whenever I encounter quit , I want to immediately exit processing the commands and ignore all other commands that are coming after it. 但是,无论何时遇到quit ,我都想立即退出处理命令,并忽略后面的所有其他命令。

I tried to do this the following way using exit() 我尝试使用exit()通过以下方式执行此操作

for(int i =0;i < numOfCommands;i++)
{
    childPid = fork();
    if(childPid == 0)
    {
        if(execvp(commands[i].cmd[0],commands[i].cmd) == -1)
         {
            /*if(strcmp(commands[i].cmd[0],"quit"))
            {
                done = true;
                return;
            }*/

            if(strcmp(commands[i].cmd[0],"quit")==0)
            {
                printf("Quit command found ! \n Quitting .");
                done = true;
                //return;
                 exit(0);


            }
            printf("Command %s is unknown \n", commands[i].cmd[0]);

        }
    }
    else 
    {
                    //parent process
        wait(&child_status);
    }
  }
}

And this happens inside of the child process, after forking of course. 当然,这是在分叉之后在子进程内部发生的。 But the problem is that my program keeps processing the remaining commands that comes after quit before exiting the program ! 但是问题是我的程序在退出程序之前会继续处理退出后剩下的命令!

You can use kill(2) to send a signal to the process group. 您可以使用kill(2)向进程组发送信号。 You can do this in the parent or any of the children. 您可以在父母或任何子女中进行此操作。

int kill(pid_t pid, int sig);

If pid equals 0, then sig is sent to every process in the process group of the calling process. 如果pid等于0,则将sig发送到调用进程的进程组中的每个进程。

For example: 例如:

kill(0, SIGTERM);

I think a better way to deal with this is to check for the quit command in the parent process before forking the child. 我认为解决此问题的更好方法是派生孩子之前检查父进程中的quit命令。

But if you want to do it in the child, you can send a signal to the parent. 但是,如果要在孩子中进行操作,则可以向父母发送信号。

kill(getppid(), SIGUSR1);

The parent process will need to establish a signal handler for SIGUSR1 that cleans everything up and exits. 父进程将需要为SIGUSR1建立一个信号处理程序,以清理所有内容并退出。 Or you could send a signal like SIGINT , whose default action is to kill the process, but it's better to implement a clean exit. 或者,您可以发送诸如SIGINT类的SIGINT ,其默认操作是终止该进程,但是最好实现一个干净的出口。

Also, in your code, you should check for the quit command before calling execvp . 另外,在代码中,应调用execvp 之前检查quit命令。 Otherwise, if there's a quit program in the user's path, it will never match your built-in quit , since execvp will succeed and not return. 否则,如果用户路径中有一个quit程序,则该程序永远不会与您的内置quit匹配,因为execvp将成功且不会返回。

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

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