linux下的C语言开发(进程等待)

来源:互联网 发布:html在线音乐源码 编辑:程序博客网 时间:2024/05/18 00:20
   所谓进程等待,其实很简单。前面我们说过可以用fork创建子进程,那么这里我们就可以使用wait函数让父进程等待子进程运行结束后才开始运行。注意,为了证明父进程确实是等待子进程运行结束后才继续运行的,我们使用了sleep函数。但是,在linux下面,sleep函数的参数是秒,而windows下面sleep的函数参数是毫秒。

[cpp] view plaincopyprint?
  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <unistd.h>   
  4.   
  5. int main(int argc, char* argv[])  
  6. {  
  7.     pid_t pid;  
  8.   
  9.     pid = fork();  
  10.     if(0 == pid)  
  11.     {  
  12.         printf("This is child process, %d\n", getpid());  
  13.         sleep(5);  
  14.     }  
  15.     else  
  16.     {  
  17.         wait(NULL);  
  18.         printf("This is parent process, %d\n", getpid());  
  19.     }  
  20.   
  21.     return 1;  
  22. }  
    下面,我们需要做的就是两步,首先输入gcc fork.c -o fork, 然后输入./fork,就会在console下面获得这样的结果。

[cpp] view plaincopyprint?
  1. [root@localhost fork]# ./fork  
  2. This is child process, 2135  
  3. This is parent process, 2134  

原创粉丝点击