参考文章:
Linux——进程(fork与vfork)
多进程编程学习笔记-1-进程基础
演示demo1
fork()和wait()
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main()
{
printf("father process-id=%d\n", getpid());
pid_t pid_fork = fork(); // if success, the pid_fork is child-process-id
if(pid_fork > 0) {
printf("This is father and father-pid = %d\n", getpid());
printf("This is father and child-pid = %d\n", pid_fork);
//
for(int i = 0; i < 2; i++) {
printf("@@@@@@@@@@@@@@ father i=%d.\n", i);
sleep(1);
}
// wait child-process finished
int stat_val ;
pid_t child_pid;
child_pid = wait(&stat_val);
printf("child-process[%d] has finished.\n", child_pid);
if(WIFEXITED(stat_val)) {
printf("child-process[%d] exited with code %d.\n", child_pid, WEXITSTATUS(stat_val));
} else {
printf("child-process[%d] terminated abnormally.\n", child_pid);
}
} else if(pid_fork == 0) {
printf("This is child and child-pid = %d\n", getpid());
for(int i = 0; i < 5; i++) {
printf("============= child i=%d.\n", i);
sleep(1);
}
} else {
printf("fork error and error is %d[%s].", errno, strerror(errno));
perror("fork error.");
exit(1);
}
return 0;
}
演示demo2
fork()和vfork()的区别
:
1)fork(): 父子进程的执行次序不确定。
?????vfork():保证子进程先运行,在它调用 exec(进程替换) 或 exit(退出进程)之后父进程才可能被调度运行。
2)fork(): 子进程拷贝父进程的地址空间,子进程是父进程的一个复制品。
?????vfork():子进程共享父进程的地址空间(准确来说,在调用 exec(进程替换) 或 exit(退出进程) 之前与父进程数据是共享的。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
// vfork()
int main()
{
int mark = 0;
pid_t pid = vfork();
while(1) {
if(pid > 0) {
printf("This is father PID:%d and mark is %d.\n", getpid(), mark);
sleep(2);
printf("father-process exit.");
break;
} else if(pid == 0) {
printf("This is child PID:%d and mark is %d.\n", getpid(), mark++);
sleep(2);
if(mark > 2) {
printf("child exit!!!\n");
exit(-1);
}
}
}
return 0;
}