问题描述
如果我使用wait(null)
,并且我(肯定)知道孩子将在父进程到达wait(null)
之前完成(退出),那么wait(null)
是否会阻塞父进程?我的意思是wait()
不会收到任何信号吗?
If i use wait(null)
, and i know (for sure) that the child will finish (exit) before we reach to wait(null)
in the parent process , does the wait(null)
block the parent process ??I mean , the wait()
won't get any signal right ?
int main() {
int pipe_descs[2] ;
int i, n, p ;
srand(time(NULL( ;
pipe(pipe_descs) ;
for (i = 0; i < 2; i++) {
pid_t status = fork() ;
if (status == 0) {
n = rand() % 100;
p = (int) getpid() ;
write(pipe_descs[1], &n, sizeof(int)) ;
write(pipe_descs[1], &p, sizeof(int)) ;
exit(0) ;
}
else {
read(pipe_descs[0], &n, sizeof(int)) ;
read(pipe_descs[0], &p, sizeof(int)) ;
printf(" %d %d\n", n, p) ;
wait(NULL) ; // (1)
}
}
return 0 ;
}
推荐答案
wait(NULL)
将阻止父进程,直到其任何子进程完成.如果子进程在父进程到达wait(NULL)
之前终止,则子进程将变为zombie process
,直到其父进程等待它并从内存中释放为止.
wait(NULL)
will block parent process until any of its children has finished. If child terminates before parent process reaches wait(NULL)
then the child process turns to a zombie process
until its parent waits on it and its released from memory.
如果父进程不等待其子进程,并且父进程先完成,则子进程将成为孤立进程,并被分配为init
作为其子进程.初始化将等待并释放进程表中的进程条目.
If parent process doesn't wait for its child, and parent finishes first, then the child process becomes orphan and is assigned to init
as its child. And init will wait and release the process entry in the process table.
换句话说:父进程将被阻止,直到子进程将退出状态返回到操作系统,然后该退出状态又返回到父进程.如果子进程在父进程到达wait(NULL)之前完成,它将读取退出状态,释放进程表中的进程条目,并继续执行直到完成为止.
In other words: parent process will be blocked until child process returns an exit status to the operating system which is then returned to parent process. If child finishes before parent reaches wait(NULL) then it will read the exit status, release the process entry in the process table and continue execution until it finishes as well.
这篇关于wait(NULL)如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!