参考文档:
【Linux系统编程】进程编程_linux while 1-CSDN博客
一、创建进程函数fork
pid_t fork(void);
fork函数调用成功,返回两次
返回值为0,代表当前进程是子进程
返回值非负数,代表当前进程为父进程
调用失败,返回-1
fork函数的作用:
是一个系统调用,它用于创建一个新的子进程。子进程是从父进程派生出来的,它会复制父进程的代码、数据和资源,并在
fork()
调用之后从父进程的返回处继续执行。
fork()
的作用如下:
原型函数:
NAME
fork - create a child process
SYNOPSIS
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
实例函数1
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid1;
pid_t pid2;
pid1 = getpid();
printf("before fork = %d",pid1);
pid2 = fork();
printf("after fork = %d",pid2);
if(pid1 == pid2) {
printf("this is father pid \r\n");
} else {
printf("this is son pid \r\n");
}
return 0;
}
实例函数2
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid1;
pid_t pid2;
pid2 = getpid();
printf("before fork = %d",pid2);
pid2 = fork();
printf("after fork = %d",pid2);
if(pid2 >0) {
printf("this is father pid \r\n");
} else if(pid2 == 0) {
printf("this is son pid \r\n");
}
return 0;
}
二、vfork函数fork有什么区别
关键区别一: vfork 直接使用父进程存储空间,不拷贝。
关键区别二: vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if(pid > 0) {
while (1)
{
printf("father love u, get pid :%d \r\n",getpid());
sleep(1);
}
}
else if(pid == 0 ) {
while (1)
{
printf("son love u, get pid :%d \r\n",getpid());
sleep(1);
}
}
return 0;
}
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = vfork();
if(pid > 0)
{
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3){
exit(0);
}
}
}
return 0;
}
三、 进程退出
正常退出
1、Main函数调用return
2、进程调用exit(),标准c库
3、进程调用_exit()或者_Exit(),属于系统调用
补充:
1、进程最后一个线程返回
2、最后一个线程调用pthread_exit
异常退出
1、调用abort
2、当进程收到某些信号时,如ctrl+C
1、最后一个线程对取消(cancellation)请求做出响应
四、等待子进程
父进程等待子进程退出,并收集子进程的退出状态
子进程退出状态不被收集,变成僵死进程(僵尸进程)
status参数: 是一个整型数指针
非空: 子进程退出状态放在它所指向的地址中
空: 不关心退出状态
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
int status = 9;
pid = vfork();
if(pid > 0)
{
while(1){
wait(&status);
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3){
exit(3);
}
}
}
return 0;
}