『阿男的Linux内核世界』*09 wait的使用方法*

『阿男的Linux内核世界』*09 wait的使用方法*

我们这篇文章里来写段代码使用wait函数:

#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  pid_t pid = fork(); // create a child process                                                                                                              

  if (pid == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
  }

  if (pid == 0) { // I am child process                                                                                                                      
    printf("child process sleep for 3 seconds...\n");
    sleep(3); // sleep for 3 seconds so parent process needs to wait child process to exit                                                                   
    printf("child process exit.\n");

  } else { // I am parent process                                                                                                                            
    printf("parent process waiting for child to exit...\n");
    wait(0); // Wait for child process to exit                                                                                                               
    printf("parent process exit\n");
  }

上面这段代码使用fork函数创建一个child process,然后让child process sleep 5秒;在parent process里,我们使用wait函数,让parent process等待child process的退出。

编译上面的代码:

$ cc wait.c -o wait

然后执行结果如下:

$ ./wait 
parent process waiting for child to exit...
child process sleep for 3 seconds...
child process exit.
parent process exit

从上面的执行过程我们可以看到parent process一定会等child process退出后,自己才退出,这就是wait函数的作用:确保了进程间的执行顺序。

关于wait函数的定义:

pid_t wait(int *status);

它的参数status的含义如下:

If status is not NULL, wait() and waitpid() store status information in the int to which it points.

也就是说,如果我们传入一个非空的status,那么wait函数会把执行结束后的child process的一些信息注入到这个status数据里。注意拿参数当返回值的一部分来使用,是C代码里面的常用技巧,大家可以熟悉一下。关于status里面具体会有什么信息,我们下次再讲。

转载于:https://my.oschina.net/u/3195023/blog/817153

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值