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

在Linux下面,创建进程是一件十分有意思的事情。我们都知道,进程是操作系统下面享有资源的基本单位。那么,在Linux下面应该怎么创建进程呢?其实非常简单,一个fork函数就可以搞定了。但是,我们需要清楚的是子进程与父进程之间除了代码是共享的之外,堆栈数据和全局数据均是独立的。

[cpp]  view plain copy
  1. #include <unistd.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <math.h>  
  5. #include <errno.h>  
  6. #include <sys/types.h>  
  7. #include <sys/wait.h>  
  8.   
  9. int main()  
  10. {  
  11.     pid_t pid;  
  12.   
  13.     if(-1 == (pid = fork()))  
  14.     {  
  15.         printf("Error happened in fork function!\n");  
  16.         return 0;  
  17.     }  
  18.   
  19.     if(0 == pid)  
  20.     {  
  21.         printf("This is child process: %d\n", getpid());  
  22.     }  
  23.     else  
  24.     {  
  25.         printf("This is parent process: %d\n", getpid());  
  26.     }  
  27.   
  28.     return 0;  
  29. }  
  30.  
  31. 所谓进程等待,其实很简单。前面我们说过可以用fork创建子进程,那么这里我们就可以使用wait函数让父进程等待子进程运行结束后才开始运行。注意,为了证明父进程确实是等待子进程运行结束后才继续运行的,我们使用了sleep函数。但是,在linux下面,sleep函数的参数是秒,而windows下面sleep的函数参数是毫秒。

    [cpp]  view plain copy
    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.     if(-1 == (pid = fork()))  
    9.       {  
    10.         printf("Error happened in fork function!\n");  
    11.         return 0;  
    12.     }  
    13.  
    14.     if(0 == pid)  
    15.     {  
    16.         printf("This is child process, %d\n", getpid());  
    17.         sleep(5);  
    18.     }  
    19.     else  
    20.     {  
    21.         wait(NULL);  
    22.         printf("This is parent process, %d\n", getpid());  
    23.     }  
    24.   
    25.     return 1;  
    26. }  
        下面,我们需要做的就是两步,首先输入gcc fork.c -o fork, 然后输入./fork,就会在console下面获得这样的结果。

    [cpp]  view plain copy
    1. [root@localhost fork]# ./fork  
    2. This is child process, 2135  
    3. This is parent process, 2134  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值