进程:
1. 进程就是处于执行器的程序。通常是调用fork系统,系统通过复制现有进程来创建新的进程。
2.每个进程都有一个task_struct数据结构,称为进程描述符和一片用作系统空间堆栈的存储空间。
3. 内核通过标识进程pid来识别进程 ,也就是pid_t 它的类型是int。
4.
进程执行的第一步:通过fork()创建一个进程。
fork 是如何运行的呢,参见 http://www.codeceo.com/article/linux-kernel-create-process.html
#include <stdio.h>
#include <unistd.h>
int main(int argc, const char * argv[]) {
// insert code here...
pid_t pid;
if((pid = fork()) == 0){
//返回0的是子进程
printf("child pid: %d\n", getpid());
} else {
printf("pid: %d\n", pid);//父进程中返回子进程的pid
printf("father pid: %d\n", getpid());
}
}
5. 生命周期
进程执行的第二部:调用execve()
创建进程的目的一般是为了执行新的目标程序, Linux提供了一个系统调用execve(), 让一个进程执行以文件形式存在的可执行程序的映像。
1 #include <stdio.h>
2.int main()
4 {
5 int child;
6 char *args[] = { "/bin/echo", "Hello", "World!", NULL};
7 8
if (!(child = fork())) //创建一个子进程
9 {
10 /* child */
11 printf("pid %d: %d is my father\n", getpid(), getppid());
12 execve("/bin/echo", args, NULL);
13 printf("pid %d: I am back, something is wrong!\n", getpid());
14 }
15 else
16 {
17 int myself = getpid(); //子进程的pid
18 printf("pid %d: %d is my son\n", myself, child);
19 wait4(child, NULL, 0, NULL); //父进程停止运行
20 printf("pid %d: done\n", myself);
21 }
22 return 0;
23 }