1.fork():系统调用创建一个与原来进程几乎完全相同的进程,且父子进程都继续执行
#include <unistd.h>
pid_t frok(void);
pid_t:定义的类型是进程号类型
返回值:成功则返回两个值,父返回子的pid,子返回0;失败则父返回-1。
出错可能:
1)当前的进程数已经达到了系统规定的上限,这时errno的值被设置为EAGAIN。
2)系统内存不足,这时errno的值被设置为ENOMEM。
PS:
1. fork()之后,父进程和子进程执行代码的顺序是不一定的。这个和内核调度算法有关。
2. fork()之前的代码父进程和子进程都会执行。
例1:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t tempPid;
tempPid = fork();
if(tempPid == -1){
perror("fork error");
}else if(tempPid > 0){//parent
printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
}else{//child
printf("child process, pid = %d, ppid = %d\n", getpid(), getppid());
}//of if
printf("......finish......");
return 0;
}//of main
【思考 1】多次执行test_fork会发现,child process后输出的ppid不等于parent process的pid,而等于1。请说明原因。
【提示】出现这种情况,是因为父进程先于子进程终止,子进程变成“孤儿进程”,后面由init进程来接收。
例2:创建多个进程
每次调用fork函数,系统会复制原程序
i=0,第一次循环,会有两份test_fork文件
i=1,第二次循环,第一份test_fork文件又会有两份test_fork文件,第二份test_fork文件也会有两份
每一次循环,进程的总数是当前进程数量的两倍,2次循环则为2的2次方=4个进程
利用for循环加以解决
test_fork2.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t tempPid;
int i;
for(i = 0; i < 2; i ++){
if((tempPid = fork()) == 0){
break;
}//of if
}//of for i
if(tempPid == -1){
perror("fork error");
}else if(tempPid > 0){//parent
printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
}else{//child
printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
}//of if
printf("......finish......");
return 0;
}//of main
2.sleep():令目前的进程暂停, 直到达到参数seconds 所指定的时间, 或是被信号所中断
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
(可与delay()作比较)
例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t tempPid;
int i;
for(i = 0; i < 2; i ++){
if((tempPid = fork()) == 0){
break;
}//of if
}//of for i
if(tempPid == -1){
perror("fork error");
}else if(tempPid > 0){//parent
sleep(2);
printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
}else{//child
sleep(i);
printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
}//of if
printf("......finish......");
return 0;
}//of main