赞
踩
用程序验证红色字体
理论:
创建子进程 pid_t fork(void)
//被调用一次,却返回两次,它可能有三种不同的返回值:
//在父进程中,fork返回新创建的子进程的PID
//在子进程中,fork返回0
//如果出错,fork返回一个负值
//用fork创建子进程时,子进程和父进程fork后面的代码是共享的,但子进程的数据空间和堆栈空间都会从父进程得到一个拷贝,二不是共享。
程序:
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
printf("Start Main Progress \n");
int iRetID =0;
int i=0 , j = 0;
iRetID = fork();
if(iRetID < 0)
{
printf("Create fork fail !!!");
return 0;
}
else if(iRetID == 0)
{
while(1)
{
printf("child process id = %d\n",getpid());
printf(" i = %d \n", i++);
printf(" j = %d \n", j);
if(i > 30) break;
sleep(2);
}
}
else
{
while(1)
{
printf("parent processid = %d\n",getpid());
printf(" i = %d \n", i);
printf(" j = %d \n", j++);
if(j > 50) break;
sleep(2);
}
}
getchar();
//system("pause");
return 0;
}
运行结果:
parent processid = 781
i = 0
j = 5
child process id = 782
i = 5
j = 0
parent processid = 781
i = 0
j = 6
child process id = 782
i = 6
j = 0
parent processid = 781
i = 0
j = 7
child process id = 782
i = 7
j = 0
parent processid = 781
i = 0
j = 8
child process id = 782
i = 8
j = 0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。