一、fork()函数的作用是创建一个进程。在应用程序调用fork()函数后,会创建一个新的进程,称做子进程,原来的进程称做父进程。从这以后,运行的已经是两个进程了,子进程和父进程都可以得到fork()的返回值。对于子进程来说,fork()函数的返回值是0,对于父进程来说,fork函数的返回的是子进程的进程号。如果创建进程失败,fork()函数会给父进程返回-1,这也是判断进程是否创建成功的依据。
1.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
pid=fork(); //创建进程后,有两个进程共享代码,都将运行 下面的代码
if(-1==pid)//创建进程失败
{
printf("Error to create new process!/n");
return 0;
}
else if(pid==0) / /子进程
{
printf("Child process!/n");
}
else //父进程
{
printf("Parent process!Child process ID:%d/n",pid);
}
return 0;
}
2.
#include <unistd.h>
#include <stdio.h>
int main(void)
{
pid_t pid;
int count=0;
pid=fork();//之后有两个进程,共享代码,都执行printf命令。
count++;
printf("count=%d/n",count);
return 0;
}
输出两次: count=1
count=1
子进程的 数据空间、堆栈空间都会从父进程得到一个拷贝,而不是共享。在子进程中对count加一的操作并没有影响父进程中count的值,父进程中的count值仍为0;
3.
在父进程中使用waitpid()函数等待指定进程号的子程序返回。
父程序结束前要等带子程序结束
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid,pid_wait;
int status;
pid=fork();
if(-1==pid)
{
printf("Error to create new process!/n");
return 0;
}
else if(pid==0)
{
printf("Child process!/n");
}
else
{
printf("Parent process!Child process ID:%d/n",pid);
pid_wait=waitpid(pid,&status,0); //等待指定进程号的子程序
"Createprocess.c" 29 lines, 419 characters
4、百度上回答别人的问题
进程一旦调用了wait,就立即阻塞自己,由wait自动分析是否当前进程的某个子进程已经退出,如果让它找到了这样一个已经变成僵尸的子进程,wait 就会收集这个子进程的信息, 并把它彻底销毁后返回;如果没有找到这样一个子进程,wait就会一直阻塞在这里,直到有一个出现为止。
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int pid1, pid2;
main()
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd);
while((pid1=fork())==-1);
if(pid1==0) //子进程1
{
lockf(fd[1],1,0);
sprintf(outpipe,"child 1 process is sending a message!");
write(fd[1],outpipe,50); //子进程1写数据到管道
sleep(5);
lockf(fd[1],0,0);
exit(0);
}
else //父进程
{
while((pid2=fork())==-1); //创建子进程2
if(pid2==0) //子进程2执行
{
lockf(fd[1],1,0); /*mutex*/
sprintf(outpipe,"child 2 process is sending a message!");
write(fd[1],outpipe,50); //子进程2向管道写数据
sleep(5);
lockf(fd[1],0,0);
exit(0);
}
else //父进程
{
wait(0); //等待子进程结束,那就是子进程1先结束了,进程1先创建的写入数据后,延时5s就/结束了
read(fd[0],inpipe,50);//读管道数据
printf("%s/n",inpipe);//输出的是child 1 process is sending a message!
wait(0); 再次等待进程结束,这里等的就是进程2.
read(fd[0],inpipe,50);//读管道数据
printf("%s/n",inpipe);//这里输出 child 2 process is sending a message!
exit(0);
}
}
}
fork()函数的作用是创建一个进程。在应用程序调用fork()函数后,会创建一个新的进程,称做子进程,原来的进程称做父进程。从这以后,运行的已经是两个进程了,子进程和父进程都可以得到fork()的返回值。对于子进程来说,fork()函数的返回值是0,对于父进程来说,fork函数的返回的是子进程的进程号。如果创建进程失败,fork()函数会给父进程返回-1,这也是判断进程是否创建成功的依据
二、vfork与fork
区别:(1)fork子进程拷贝父进程的数据段
vfork子进程共享父进程数据段
(2)fork子进程父进程执行次序不确定
vfork子进程先运行、父进程后运行
#include <unistd.h>
#include <stdio.h>
int main(void)
{
pid_t pid;
int count=0;
pid=vfork();//之后有两个进程,共享代码,共享数据段,都执行printf命令。
count++;
printf("count=%d/n",count);
return 0;
}
输出两次: count=1
count=2