如何创建进程
在linux下创建进程一般用fork()函数来实现,fork中文的意思大概是“分叉”的意思,很形象贴切。fork函数的作用是复制一个与当前进程一样的进程。新进程的所有数据(变量、环境变量、程序计数器等)数值都和原进程一致,只有进程标识符(PID)不一样。原进程叫父进程,从原进程克隆出来的新进程叫该原进程的子进程。子进程跟原进程运行的是相同的程序。就像下图一样(图片来自head.first.c )
Linux 进程编程
fork调用的一个奇妙之处就是它仅仅被调用一次,却能够返回两次,它可能有三种不同的返回值:
- 在父进程中,fork返回新创建子进程的进程ID
- 在子进程中,fork返回0
- 如果出现错误,fork返回一个负值
下面是一段简单的进程程序,运行结果会是?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
char *child = "I am child, my pid is:";
char *father = "I am father, my pid is:";
int main(int argc, char const *argv[])
{
pid_t pid;
int num = 0;
pid = fork();
if(pid < 0){
printf("fork error!!!\n");
}
else if(pid == 0){
printf("%s %d\n", child, getpid());
num ++;
}
else{
printf("%s %d\n", father, getpid());
num ++;
}
printf("%d\n",num);
return 0;
}
上面说过子进程跟原进程运行的是相同的程序。所以就不难猜出结果。
I am father, my pid is: 5842
num is : 1
I am child, my pid is: 5843
num is : 1
再来看看这个更简短的程序(一道面试题)
#include "stdio.h"
#include "sys/types.h"
#include "unistd.h"
int main()
{
pid_t pid1;
pid_t pid2;
pid1 = fork();
pid2 = fork();
printf("pid1:%d, pid2:%d\n", pid1, pid2);
return 0;
}
已知从这个程序执行到这个程序的所有进程结束这个时间段内,没有其它新进程执行。
1、请说出执行这个程序后,将一共运行几个进程。
2、如果其中一个进程的输出结果是“pid1:1001, pid2:1002”,写出其他进程的输出结果(不考虑进程执行顺序)。
我们先看结果如何,再来分析下。
pid1:25519, pid2:25520
pid1:25519, pid2:0
pid1:0, pid2:25521
pid1:0, pid2:0
下面我画个图分析下,那就很明了了,注意图中的父进程和子进程是相对而言的。
从上图再来回答上面的问题就很简单了,首先第一问就是一共运行了4个进程,其中一个进程输出是“pid1:1001, pid2:1002”,那么其他三个进程输出就是“pid1:1001, pid2:0”“pid1:0, pid2:1003”“pid1:0, pid2:0”
参考
- linux中fork()函数详解(原创!!实例讲解) http://blog.csdn.net/jason314/article/details/5640969#comments
- Linux进程基础知识总结 http://www.jellythink.com/archives/900
- 从一道面试题谈linux下fork的运行机制 http://www.cnblogs.com/leoo2sk/archive/2009/12/11/talk-about-fork-in-linux.html
- 进程与线程的一个简单解释 http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html