/***********************************fork & vfork*********************************/1
1. fork:子进程拷贝父进程的数据段
vfork: 子进程与父进程共享数据段
2. fork: 父、子进程的执行顺序是随机的
vfork: 先执行子进程,后执行父进程
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("fork = %d\n",getpid());
if(argc != 3)
{
printf("Please input two param!\n");
exit(1);
}
int i;
for(i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n",i,argv[i]);
}
pid_t pid;
/*此时仅有一个进程,*/
int count = 0;
pid = fork();
/*此时已经有两个进程在运行了*/
if(pid < 0)
{
perror("fork error!");
exit(1);
}
if(pid == 0)
{
count++;
printf("child count = %d\n",count);
sleep(5);
exit(1); // 使用vfork创建子进程时,必须要使用exit(1)来异常退出子进程,这样才能使得父、子进程共享的数据段来不及被释放,如果正常退出,会导致vfork创建的父进程执行已经被子进程释放的数据段,从而出现段错误。
}
else
{
count++;
printf("parent count = %d\n",count);
}
/************************************************************************************/
/***********************************fork.c****************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("fork = %d\n",getpid());
if(argc != 3)
{
printf("Please input two param!\n");
exit(1);
}
int i;
for(i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n",i,argv[i]);
}
pid_t pid;
/*此时仅有一个进程,*/
int count = 0;
pid = fork();
/*此时已经有两个进程在运行了*/
if(pid < 0)%s
{
perror("fork error!");
exit(1);
}
if(pid == 0)
{
count++;
printf("child count = %d\n",count);
sleep(5);
exit(1); //
}
else
{
count++;
printf("parent count = %d\n",count);
}
/************************************hello.c****************************************/
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("hello world! = %d\n",getpid());
//execl("/root/0207/fork","./fork","hello1","hello2",NULL); 第三种创建子进程的方法
char *argv[] = {"./fork","hello1","hello2",NULL};
//execv("/root/0207/fork",argv);
system("./fork hello1 hello2"); 第四种创建子进程的方法
while(1)
{
printf("hello!\n");
sleep(1);
}
return 0;
}
/***********************************************************************************/