您的位置:首页 > 大数据 > 人工智能

wait() 和 waitpid()

2016-09-23 09:45 197 查看
wait() 和waipid()

子进程比父进程先结束执行,则子进程将成为僵死进程

父进程比子进程先结束,则子进程将成为孤儿进程,他将有init (pid =1)收养;

主动调用wait() 和 waitpid() 的进程A可能发生什么?

    如果他的子进程还在运行,则A进程阻塞

    如果他的子进程已经停止,则正在等待的进程A会立即返回,

    如果进程A没有子进程,在返回出错;

#include<sys/wait.h>

wait(int *status)

waitpid(pid_t pid,int *status,int options)

    返回值:成功,返回进程ID,出错 返回0

    

pid == -1 等待任意一子进程 == wait()

pid > 0   等待进程ID == pid 的进程

pid == 0  等待组ID == 调用进程组ID 的任意 一子进程

pid < 0   等待组ID 等于pid 绝对值的任意一子进程

waitpid 提供的功能比wait 多的3 个功能

    可以等待制定进程

    提供了不阻塞版本wait

    支持作业控制

有多少个子进程就应该有几个wait 或waitpid()

#include<sys/wait.h>
void exitAnalyse(int status)
{
if(WIFEXITED(status))
{
cout<<"normal::"<<WEXITSTATUS(status)<<endl;
}
if(WIFSIGNALED(status))
{
cout<<"abnormal::"<<WTERMSIG(status)<<"; "<<WCOREDUMP(status)<<endl;
}
if(WIFSTOPPED(status))
{
cout<<"Stop::"<<WSTOPSIG(status)<<endl;
}
}
void waitTest()
{
int status =0;
pid_t pid = fork();
if(pid ==0)
{
cout<<"child___1..pid = "<<getpid()<<endl;
// sleep(1);
exit(1);
}
else
{
cout<<"parent___1"<<endl;
}
pid = fork();
if(pid ==0)
{
cout<<"child___2..pid = "<<getpid()<<endl;
sleep(5);
return;
}
else
{
cout<<"parent___2"<<endl;
}
/*
int x;
x = wait(&status);
cout<<"parent end : "<<x<<endl;
exitAnalyse(x);
x = wait(&status);
cout<<"parent end : "<<x<<endl;
exitAnalyse(x);
*/
cout<<waitpid(pid,NULL,WNOHANG)<<endl;
sleep(22);
}
int main()
{
cout<<"=====waitTest======"<<endl;
waitTest();
return 1;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: