linux中fork的使用
fork用于创建进程的内容,在linux中,可以在一个主线程中,创建子线程;
两个进程之间的内容是独立的,互补影响的;
pid_t pid = fork();
该函数会返回两个值,返回子线程的pid,子线程则会返回0;
#include <iostream>
#include <stdio.h>
#include <unistd.h>
using namespace std;
int main()
{
int i = 0;
cout<<"before fork"<<endl;
pid_t pid = fork();
cout<<"after fork"<<endl;
if(pid < 0)
{
cout<<"error"<<endl;
return 1;
}
else if(pid == 0)
{
cout<<"fork sucess, this is son process"<<endl;
while(i < 10)
{
i += 1;
cout<<"this is son process, i = "<<i<<endl;
sleep(1);
}
}
else
{
cout<<"fork sucess, this is father process, son process pid="<<pid<<endl;
while(i < 10)
{
i += 2;
cout<<"this is father process i="<<i<<endl;
sleep(2);
}
}
cout<<"process destroy"<<endl;
return 0;
}
最后的输出结果为:
before fork
after fork
fork sucess, this is father process, son process pid=4349
this is father process i=2
after fork
fork sucess, this is son process
this is son process, i = 1
this is son process, i = 2
this is son process, i = 3
this is father process i=4
this is son process, i = 4
this is son process, i = 5
this is father process i=6
this is son process, i = 6
this is son process, i = 7
this is father process i=8
this is son process, i = 8
this is son process, i = 9
this is father process i=10
this is son process, i = 10
process destroy
process destroy