#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
//进程的特点
// 1.能实现多任务
// 2.执行顺序取决于cpu
// 3.fork创建的父子进程资源不共享
//#include<fcntl.h>
//1.实现多任务
void test01()
{
pid_t pid=fork();
if(0>pid)
{
perror("fork error");
}
else if(0==pid)//子进程返回0
{
printf("子进程返回的pid:%d\n",pid);//输出0
printf("子进程的id:%d\n",getpid());
while(1)
{
printf("这是一个子进程\n");
sleep(1);
}
}
else//父进程中返回子进程的ID
{
printf("子进程返回的pid:%d\n",pid);//输出子进程的id
while(1)
{
printf("这是一个父进程\n");
sleep(1);
}
}
}
//2.父、子进程的执行顺序由cpu决定,资源不共享
void test02()
{
int num=10;
pid_t pid2=fork();
if(0>pid2)
{
perror("fork error");
}
else if(0==pid2)//子进程返回0
{
while(1)
{
printf("num1=%d",num);
printf("这是一个子进程\n");
sleep(1);
}
}
else//父进程中返回子进程的ID
{
while(1)
{
num++;
printf("num2=%d",num);
printf("这是一个父进程\n");
sleep(1);
}
}
}
//3.当正常执行程序./a.out,行缓冲就是行缓冲,如果将程序重定向,行缓冲变成全缓冲。
void test03()
{
write(1,"hahahhahh",strlen("hahahhahh"));
printf("行缓冲\n");
printf("全缓冲");
pid_t pid3=fork();
if(pid3<0)
{
perror("fork error");
}
else if(0==pid3)
{
fflush(NULL);
}
else
{
fflush(NULL);
}
while(1);
}
//4.多进程的创建方式1,产生2的n次方个进程,进程愈多,进程的判定越麻烦,
//
void test04()
{
pid_t pid_1=fork();
pid_t pid_2=fork();
if(pid_1==0&&pid_2>0)
{
printf("子进程1\n");
printf("子进程1PID:%d PPID:%d\n",getpid(),getppid());
}
else if(pid_1>0&&pid_2==0)
{
printf("子进程2\n");
printf("子进程2PID:%d PPID:%d\n",getpid(),getppid());
}
else if(pid_1==0&&pid_2==0)
{
printf("孙子进程\n");
printf("孙子进程PID:%d PPID:%d\n",getpid(),getppid());
}
else
{
printf("父进程\n");
printf("父进程PID:%d\n",getpid());
}
while(1);
}
//4.1 多进程的创建方式2 进程等待wait
void test05()
{
int sta;
int i=0;
for(i=0;i<3;i++)
{
pid_t pid_3=fork();
if(pid_3==0)
{
break;
}
}
if(i==0)
printf("子进程1 %d---%d\n",getpid(),getppid());
else if(i==1)
printf("子进程2 %d-----%d\n",getpid(),getppid());
else if(i==2)
printf("子进程3 %d------%d\n",getpid(),getppid());
else if(i==3)
{
printf("父进程 %d\n",getpid());
//pid_t pid_3=wait(&sta); /*一次只等待一个*/
//pid_t pid_3=waitpid(-1,&sta,0); /* 阻塞等待任意进程结束,也只等一个*/
printf("回收的子进程的id:%d\n",pid_3);
}
}
int main()
{
test05();
return 0;
}
01 线程fork
最新推荐文章于 2024-01-31 20:58:41 发布