赞
踩
摘要:本文详解介绍fork()函数的基本使用,以及父子进程之间的关系.子进程对变量的改变不会影响到父进程、子进程对父进程文件流缓冲区的处理和子进程对父进程打开的文件描述符的处理.
创建进程
子进程在创建后和父进程同时执行,竞争系统资源,谁先谁后,取决于内核所使用调度算法.子进程的执行位置为fork返回位置.
2.创建子进程
例子1:演示fork函数的基本使用方法.- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- int main()
- {
- pid_t pid;
- if((pid=fork())==-1)
- printf("fork error\n");
- printf("a example of fork,pid = %d\n",getpid());
- return 0;
- }
输出:
:a example of fork,pid = 2798- #include <stdio.h>
- #include <sys/types.h>
- #include <unistd.h>
- int main()
- {
- pid_t pid;
- if((pid=fork())==-1)
- {
- printf("fork error\n");
- }
- else if(pid == 0 )
- {
- printf("pid:%d in the child process \n",pid);
- }
- else
- {
- printf("pid:%d in the parent process\n",pid);
- }
- return 0;
- }
输出:
:pid:2923 in the parent process- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- int glob = 10;
- int main()
- {
- int var = 100;
- pid_t pid = getpid();
- printf("before fork:\n");
- printf("pid=%d, glob=%d, var=%d\n",pid,glob,var);
-
- printf("after fork:\n");
- if((pid=fork())<0)
- {
- printf("error fork:%m\n");
- exit(-1);
- }
- else if(pid==0)
- {
- glob++;
- var++;
- }
- else
- {
- sleep(2);
- }
-
- printf("pid = %d, glob = %d, var = %d\n",getpid(),glob,var);
- return 0;
- }
输出:
:before fork:- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- int main()
- {
- pid_t pid;
-
- //有回车,先输出
- printf("before fork,have enter\n");
-
- //没有回车,先输出到缓冲区
- printf("before fork,no enter:pid=%d\t",getpid());
- pid = fork();
- if(pid == 0)
- {
- printf("\nchild,after fork:pid=%d\n",getpid());
- }
- else
- {
- printf("\nparent,after fork: pid=%d\n",getpid());
- }
- return 0;
- }
输出:
:before fork,have enter- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <fcntl.h>
-
- int main()
- {
- pid_t pid;
- int fd;
- int i=1;
- int status;
- char *ch1="advanced";
- char *ch2=" programming";
- char *ch3=" int the unix Environment";
-
- fd = open("test.txt",O_RDWR|O_CREAT,0644);
- if(fd==-1)
- {
- printf("open or creat file error:%m\n");
- exit(-1);
- }
- write(fd,ch1,strlen(ch1));
- pid=fork();
- if(pid==-1)
- {
- printf("error fork\n");
- exit(-1);
- }
- else if(pid==0)
- {
- i=2;
- printf("in child process\n");
- printf("i=%d\n",i);
- if(write(fd,ch2,strlen(ch2))==-1)
- {
- printf("child write error:%m\n");
- exit(-1);
- }
- }
- else
- {
- sleep(1);
- printf("int parent process\n");
- printf("i=%d\n",i);
- if(write(fd,ch3,strlen(ch3))==-1)
- {
- printf("parent wirte error%m\n");
- exit(-1);
- }
- wait(&status);
- }
-
- return 0;
- }
输出:cat test.txt
:advanced programming int the unix EnvironmentCopyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。