目录
一、创建进程函数fork
pid_t fork(void);
fork函数调用成功,返回两次
返回值为0,代表当前进程是子进程
返回值非负数,代表当前进程为父进程
调用失败,返回-1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid_t pid2;
pid_t retpid;
pid = getpid();
printf("before fork: pid = %d\n",pid );
retpid = fork();
pid2 = getpid();
printf("after fork: pid = %d\n",pid2 );
if(pid == pid2)
{
printf("this is father print: retpid = %d,father pid = %d\n",retpid,getpid());
}
else{
printf("this is child print: retpid = %d,child pid = %d\n",retpid,getpid());
}
return 0;
}
补充forktest:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int data = 10;
printf("father: pid=%d\n",getpid());
pid = fork();
if(pid > 0)
{
printf("this is father print, pid = %d\n",getpid());
}
else if(pid == 0){
printf("this is child print,child pid = %d\n",getpid());
data = data+100;
}
printf("data=%d\n",data);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int data = 10;
while(1){
printf("please input a data\n");
scanf("%d",&data);
if(data == 1){
pid = fork();
if(pid > 0)
{
}
else if(pid == 0){
while(1){
printf("do net request,pid=%d\n",getpid());
sleep(3);
}
}
}
else{
printf("wait ,do nothing\n");
}
}
return 0;
}
二、vfork函数fork有什么区别
关键区别一: vfork 直接使用父进程存储空间,不拷贝。
关键区别二: vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行。
1、fork
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if(pid > 0)
{
while(1){
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);
}
}
return 0;
}
2、vfork
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#inclu