关于fork

来源:互联网 发布:java界面设计关闭 编辑:程序博客网 时间:2024/05/16 05:34

头文件:

#include<unistd.h>
#include<sys/types.h>

      一个现有进程可以调用fork函数创建一个新进程。由fork创建的新进程被称为子进程(child process)。fork函数被调用一次但返回两次。两次返回的唯一区别是子进程中返回0值而父进程中返回子进程ID。


#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>


int main()
{
int i;
if(fork()==0){//子进程
for(i=0; i<5; i++){
printf("myid=%d,parent=%d\n",getpid(),getppid());
sleep(1);
}
return 123;
}
else if(fork()==0){//子进程
for(i=0; i<10; i++){
printf("myid=%d,parent=%d\n",getpid(),getppid());
sleep(1);
}
return 234;
}
else{//父进程
for(i=0; i<20; i++){
write(2,"+",1);
int s;
pid_t cid = wait(&s);
if(cid>0){
printf("child %d exited.\n", cid);
if(WIFEXITED(s))
printf("ret:%d\n",WEXITSTATUS(s));   //获取子进程结束方式也就是一个值
}
sleep(1);
}
}
return 0;
}


0 0
原创粉丝点击