fork()指令
One call,Two return.返回值若为0,说明当前在子进程中;返回值大于0,说明在父进程中,返回值为其子进程的PID
getpid()
返回当前进程的ID
waitpid(pid_t pid,int *statusp,int options)
- pid:
pid>0时只等待进程ID为pid的子进程结束
pid=-1时等待其所有的子进程中的任何一个(只要一个)结束
- options:
options=0(默认情况)时,挂起父进程,等待其子进程结束。返回子进程编号。
options=WNOHANG时,父进程不挂起。如果一个子进程都没有结束的话,返回0;否则返回子进程编号。
- 如果调用函数的进程没有子进程,waitpid返回-1,errno设为ECHILD
wait(&status)
等价于waitpid(-1,&status,0)
WIFEXITED(status):
如果子进程是以exit或者return正常退出的,函数返回值就为true
WEXITSTATUS(status)
前提是WIFEXITED一定为true,此函数返回正常终止的子进程的退出状态,即exit的值
atexit()
在进程结束调用exit时,调用atexit()括号中的注册函数,注册几次就调用几次。并且它的调用顺序和登记顺序是相反的。与压栈顺序有关。
相关习题
- CSAPP书上部分
preparation:
1.http://csapp.cs.cmu.edu/public/code.html 下载.tar文件解压,包含了CSAPP书上的所有代码
2.运行sudo mv csapp.h /usr/include和sudo mv csapp.c /usr/include ,然后再usr/include中修改csapp.h在#endif 之前添加 #include"csapp.c"(我用的vi)
3.在gcc的时候最后加上-lpthread就可以
关于下列代码中用到的Fork和Wait在csapp.c中的定义:
/* $begin forkwrapper */
pid_t Fork(void)
{
pid_t pid;
if ((pid = fork()) < 0)
unix_error("Fork error");
return pid;
}
/* $end forkwrapper */
/* $begin wait */
pid_t Wait(int *status)
{
pid_t pid;
if ((pid = wait(status)) < 0)
unix_error("Wait error");
return pid;
}
/* $end wait */
*8.11这个程序会输出多少个"hello"输出行?
#include "csapp.h"
int main()
{
int i;
for(i=0;i<2;++i)
Fork();
printf("hello\n");
exit(0);
}
运行结果:
一共四行
进程图:
*8.12这个程序会输出多少个hello输出行?
#include "csapp.h"
void doit()
{
Fork();
Fork();
printf("hello\n");
return;
}
int main()
{
doit();
printf("hello\n");
exit(0);
}
总共8行hello
进程图:
*8.13下面程序的一种可能的输出是什么?
#include "csapp.h"
int main()
{
int x = 3;
if (Fork() != 0)
printf("x=%d\n", ++x);
printf("x=%d\n", --x);
exit(0);
}
运行结果:
可能的结果应该还有
和
*8.14下面这个程序会输出多少个"hello"输出行?
/* $begin forkprob5 */
#include "csapp.h"
void doit()
{
if (Fork() == 0) {
Fork();
printf("hello\n");
exit(0);
}
return;
}
int main()
{
doit();
printf("hello\n");
exit(0);
}
/* $end forkprob5 */