fork()函数,Linux系统调用
头文件:
#include <unistd.h>
函数定义:
int fork( void );
返回值:
子进程中返回0,父进程中返回子进程ID,出错返回-1
函数说明:
一个现有进程可以调用fork函数创建一个新进程。由fork创建的新进程被称为子进程(child process)。fork函数被调用一次但返回两次。两次返回的唯一区别是子进程中返回0值而父进程中返回子进程ID。
子进程是父进程的副本,它将获得父进程数据空间、堆、栈等资源的副本。注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间,它们之间共享的存储空间只有代码段。
示例代码:
#include <unistd.h>
#include <stdio.h>
int main(int argc, void ** argv )
{
int pid = fork();
if(pid < 0 ) {
// print("error!");
} else if( pid == 0 ) {
// print("This is the child process!");
} else {
// print("This is the parent process! child process id = %d", pid);
}
return 0;
}
头文件:
#include <unistd.h>
函数定义:
int fork( void );
返回值:
子进程中返回0,父进程中返回子进程ID,出错返回-1
函数说明:
一个现有进程可以调用fork函数创建一个新进程。由fork创建的新进程被称为子进程(child process)。fork函数被调用一次但返回两次。两次返回的唯一区别是子进程中返回0值而父进程中返回子进程ID。
子进程是父进程的副本,它将获得父进程数据空间、堆、栈等资源的副本。注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间,它们之间共享的存储空间只有代码段。
示例代码:
#include <unistd.h>
#include <stdio.h>
int main(int argc, void ** argv )
{
int pid = fork();
if(pid < 0 ) {
// print("error!");
} else if( pid == 0 ) {
// print("This is the child process!");
} else {
// print("This is the parent process! child process id = %d", pid);
}
return 0;
}