#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/types.h>
void main()
{
pid_t pid;
char *message;
int n;
printf(“fork program starting\n”);
pid=fork();
switch(pid)
{
case -1:
perror(“fork failed”);
exit(1);
case 0:
message=“this is the child”;
n=5;
break;
default:
message=“this is the parent”;
n=3;
break;
}
for(;n>0;n–)
{
puts(message);
sleep(1);
}
exit(0);
}
这是引自一本linux c程序设计类型的书上的demo源码
fork只有3种返回值。
1.返回-1,表示这个fork函数执行失败了。
2.返回0表示执行成功了,把父进程的代码和内存都拷贝到了子进程,然后子进程会跟着代码继续执行下去,这时候做的仅仅是正常打开新进程的一半操作,还有一个通过exec函数来完成,他会把进程空间的内容全部替换掉要执行的可执行文件里面的内容。
3.返回的是子进程的pid值,表示是父进程继续从这个地方执行下去。
fork函数
最新推荐文章于 2021-05-04 03:36:40 发布