简体   繁体   English

执行完后杀死一个子进程(在fork之后)

[英]killing a child process (after fork) once its execution is done

I m writing a simple web server. 我正在编写一个简单的Web服务器。 The program in simplified form is as follows 程序的简化形式如下

while(1)
{
     // accepting the connection.
     accept();

     pid = fork();

     if(pid == 0)
     { 
          // performing some operations
          _exit(EXIT_SUCCESS);

     } else {

          sleep(1);
     }
}

So once the child process executes it should terminate, and the parent process should continue accepting the connection. 因此,一旦子进程执行,它便应终止,而父进程应继续接受连接。 But, for me the child process is not getting terminated and even it(child) is also accepting the connections. 但是,对我来说,子进程不会终止,甚至它(子进程)也接受连接。 Am I doing any mistake here. 我在这里犯任何错误吗?

I am able to see the process (child) not being killed using. 我能够看到该进程(子进程)没有被杀死。

top -U <username>

I need help on this. 我需要帮助。 Thanks in advance. 提前致谢。 :) :)

The parent process has to call wait to "reap" the child process. 父进程必须调用wait以“收获”子进程。

The reasons you need to "wait" for the children is because there are still resources left after a process exits, for the exit code of the child process. 您需要“等待”子进程的原因是因为在退出进程后,仍然存在用于子进程的退出代码的资源。 What wait (and its sibling system calls) are doing is not only waiting for child processes to end, but also get the exit code so the child process can be cleaned up properly by the operating system. wait (及其同级系统调用)所做的不仅是等待子进程结束,还获得退出代码,以便操作系统可以正确清理子进程。 If the parent process doesn't wait for all child processes to exit before itself exits, then all child processes becomes orphaned, and the process with process id 1 is set as their parent. 如果父进程在退出之前不等待所有子进程退出,则所有子进程将变为孤立进程,并将进程ID为1的进程设置为其父进程。

First of all thanks everyone for helping me out. 首先,感谢大家对我的帮助。 I got the mistake in my code. 我的代码有误。 :) :)

The problem was once after accepting the connection and forking, within the child process I got to close() the socket connection using the file descriptor used in accept method like 问题出在接受连接和分支之后,在子进程中,我使用诸如accept方法之类的文件描述符close()了socket连接。

accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

then close(sockfd) should be called within the child process. 然后应该在子进程中调用close(sockfd) Since, it was not being closed in the child process, the socket was alive for accept() connections. 由于未在子进程中关闭该套接字,因此该套接字仍在accept()连接。 So, nevertheless _exit() was given the child process won't be terminated until the associated socket file descriptor is closed. 因此,尽管如此,在关闭关联的套接字文件描述符之前,不会给_exit()子进程终止。

along with this within the parent process we got to call wait() or waitpid() depending on your need for the child process to be removed from the process table and avoiding its zombie state. 与此相关,在父进程中,我们必须调用wait()waitpid()具体取决于您需要从进程表中删除子进程并避免其僵尸状态。

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

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