本文研究的主要是Linux进程函数fork(),vfork(),execX()的相关内容,具体介绍如下。
函数fork()
fork函数:创建一个新进程
1、fork()成功后,将为子进程申请PCB和用户内存空间。
2、子进程会复制父进程用户空间的所有数据(代码段、数据段、BSS、堆、栈),文件描述符。
3、复制父亲进程PCB中绝大多数信息。
4、虽然子进程复制了文件描述符,而对于文件描述符相关的文件表项(struct file结构),则采用共享的方式。
一个实例:
#include//fork fuction#include //file operator#include #include #include //exit fuction#include int main() { pid_t pid; int i=1; int status; char *ch1="hello",*ch2="world",*ch3="IN"; int fd; if ((fd=open("fork.txt",O_RDWR|O_CREAT,0644))==-1) { perror("not open"); exit(EXIT_FAILURE); } if (write(fd,ch1,strlen(ch1))==-1) { //write in fork.txt perror("not write"); exit(EXIT_FAILURE); } if ((pid=fork())==-1) { perror("fork error"); exit(EXIT_FAILURE); } else if(pid==0) { //son process int i=2; //change i printf("child:i=%d/n",i); if (write(fd,ch2,strlen(ch2))==-1) perror("child write"); return 0; } else { sleep(1); printf("parent:i=%d/n",i); if (write(fd,ch3,strlen(ch3))==-1) perror("child write"); wait(&status); return 0; }}
评论列表()