(转) Linux进程线程学习笔记:进程创建

从代码角度来看,创建一个新进程的函数声明如下:

pid_t fork(void);

其包含在 unistd.h 头文件中,其中pid_t是表示“type of process id”的32位整数, 至于函数的返回值,取决于在哪个进程中来检测该值,如果是在新创建的进程中,其为0;如果是在父进程中(创建新进程的进程),其为新创建的进程的id; 如果创建失败,则返回负值。

我们看下面的代码:

 

 1 #include <stdio.h>
 2 
 3 #include <unistd.h>
 4 
 5 int main ()
 6 {
 7     printf("app start...\n");
 8     pid_t id = fork();
 9     if (id<0) {
10         printf("error\n");
11     }else if (id==0) {
12          printf("hi, i'm in new process, my id is %d \n", getpid());
13     }else {
14         printf("hi, i'm in old process, the return value is %d\n", id);
15     }
16 return 017 }
18              

 

 

 

结果为:

fork函数失败的原因主要是没有足够的资源来进行创建或者进程表满,如果是非root权限的账户,则可能被管理员设置了最大进程数。一个用户所能创建的最大进程数限制是很重要的,否则一句代码就可能把主机搞当机:for(;;) fork(); 

再看下面的代码:

#include <stdio.h>

#include <unistd.h>



int main ()

{

    printf("app start...\n");

    

    int counter = 0;

    

    fork();

    

    counter++;

    

    printf("the counter value %d\n", counter);

    

    return 0;

}

输出为:

app start...
the counter value 1
the counter value 1

 

posted @ 2014-12-05 15:54  DancingWing  阅读(98)  评论(0)    收藏  举报