vtun fork函数

头文件:

#include<unistd.h>

#include<sys/types.h>

原型:

pid_t fork( void);

返回值:

若成功调用一次则返回两个值,子进程返回0,父进程返回子进程ID;否则,出错返回-1.

功能:

一个现有进程可以调用fork函数创建一个新进程。由fork创建的新进程被称为子进程(child process)。fork函数被调用一次但返回两次。两次返回的唯一区别是子进程中返回0值而父进程中返回子进程ID

image

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include<sys/types.h> //对于此程序而言此头文件用不到
#include<unistd.h>
#include<stdio.h>
int main(int argc, char ** argv )
{
    int pid = fork();
    if(pid < 0)
    {
        printf("error!");
    }
    else
    {
        if( pid == 0 )
        {
            printf("This is child process!\n");
        }
        else 
        {
            printf("This is the parent process! child process id = %d\n", pid);
        }
    }
    return 0;
}

/*

root@ubuntu:~/eclipseworkspace# ./a.out
This is the parent process! child process id = 4300
This is child process!
*/

原文地址:https://www.cnblogs.com/helloweworld/p/2701196.html