fork执行一次产生两个进程:一个子进程和进程本身(父进程)
pid = fork(); fork()产生的子进程pid=0(标记子进程创建成功),pid = -1(标记子进程创建失败);
**当子进程创建成功后,返回给父进程一个pid号,创建失败后返回给父进程 -1; 当返回 -1 时,父进程仍然有自己的ppid,而子进程创建失败,返回一个errno号,告诉系统子进程是如何创建失败的。
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
using namespace std;
int main()
{
pid_t pid;
pid = fork();
if(pid == 0){
//child
printf("I am child process, pid = %d\n", getpid());
printf("ppid = %d\n", getppid());
}else if(pid > 0){
//parent
printf("I am parent process, pid = %d\n", getpid());
printf("ppid = %d\n", getppid());
}else{
printf("errno = %d\n", errno);
printf("create child error\nd");
}
return 0;
}
子进程创建成功后的结果为:
[root@localhost mine]# ./fork
I am parent process, pid = 6654
ppid = 6400
I am child process, pid = 6655
ppid = 6654
[root@localhost mine]#
注意:这里不一定先运行父进程,至于父子进程先运行谁后运行谁由操作系统和调度算法决定
父子进程共享代码段,但是各自保存有自己数据
例如:
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
using namespace std;
int main()
{
int a = 0;
pid_t pid;
pid = fork();
int fd[2];
int b = 0;
if(pid == 0)
{
a = 10;
b = 20;
printf("child a = %d,b = %d\n",a,b);
sleep(2);
}
else if(pid > 0)
{
int status;
wait(&status);
printf("a = %d, b=%d\n",a,b);
}
return 0;
}
输出结果如下:
[root@localhost test5_13]# ./fork
child a = 10,b = 20
a = 0, b=0
[root@localhost test5_13]#
再如:
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
using namespace std;
int main()
{
int a = 0;
pid_t pid;
pid = fork();
int fd[2];
int b = 0;
if(pid == 0)
{
a = 10;
b = 20;
printf("child a = %d,b = %d\n",a,b);
sleep(2);
}
else if(pid > 0)
{
a = 100;
b = 200;
int status;
wait(&status);
printf("a = %d, b=%d\n",a,b);
}
return 0;
}
执行结果如下:
[root@localhost test5_13]# g++ fork.cpp -o fork
[root@localhost test5_13]# ./fork
child a = 10,b = 20
a = 100, b=200
[root@localhost test5_13]#