The purpose of the wait() in parent c

前端 未结 3 1662
北恋
北恋 2021-01-27 14:40

I am new to processes in linux and c. I am using this straightforward example:

#include 
#include 
#include 

int         


        
相关标签:
3条回答
  • 2021-01-27 15:08

    after the fork, you'll have two independent process.

    whit the wait() call, you tell the parent process to wait the child process to terminate.

    In this example, nothing changes since the two process are not interacting with each other, so the parent can just exit after creating the child and printing the string, but in the scenario where the parent has to wait the child to do some operations and then maybe return some values to the parent, it becomes useful!

    0 讨论(0)
  • 2021-01-27 15:28

    The system call wait(2) is typically used to find if the child process's state has changed (i.e. whether it's still running, exited, etc).

    Another purpose is to avoid "zombie" processes. If parent process doesn't wait on the child process and the child process exits before the parent process then it becomes a "zombie" process. So, a wait() call is used to "reap" the process and release the system resources associated with the process.

    Imagine if the parent process is a long running one and creates several child processes at regular intervals then all the zombie processes will have entries in the process table which is an unncessary use of system resources.

    0 讨论(0)
  • 2021-01-27 15:29

    Wait is for listening to state changes and obtaining information about the child. A state change is child termination, stopping or resuming by a signal. Wait allows the system to release the resources associated with the child. If a wait is not performed, then the terminated child remains in a "zombie" state.

    The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes. If a parent process terminates, then its "zombie" children (if any) are adopted by init(1), which automatically performs a wait to remove the zombies.

    0 讨论(0)
提交回复
热议问题