动机
父子进程利用exit()
和wait()
进行简单同步控制。
示例1:简单同步控制
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
int main() {
pid_t child1;
pid_t child2;
if ((child1=fork()) == -1) {
// 创建失败
printf("Fork Error.\n");
exit(1);
}
if (child1 == 0) {
// 子进程1
sleep(1);
printf("************** Now it is in first child process.I am %d\n",getpid());
printf("************** I am first child process. I'm dying. I am %d\n",getpid());
exit(0); // 注意下,注释与否,执行情况的差异。
}
else {
// 父进程
printf("Now it is in parent process.I am %d\n",getpid());
printf("I have first child %d.\n",child1);
printf("I'll wait for the termination of my child. Before that, I'm going to go into a blocking state.\n");
wait(); // 注意下,注释与否,执行情况的差异。
pri