进程管理

进程创建使用系统调用fork()vfork(),在内核中,这些函数是通过clone()系统调用完成的。进程通过系统调用exit()退出。父进程通过系统调用wait4()系统调用来查询一个停止的子进程的状态。基于wait4()系统调用的C函数有wait(),waitpid(),wait3()wait4()

进程采用数据结构task_struct描述,structthread_info为进程的一个辅助数据结构,一般存储在进程栈的边界处,通过它可以引用实现的进程数据结构地址。进程描述符是进程的唯一标识。最大进程数可通过/proc/sys/kernel/pid_max.来修改,默认为32768.

current引用当前的进程,在X86上,它等于current_thread_info()->task进程的状态可以通过如下函数进行设置:

set_task_state(task,state);

方法set_current_state(state)等同于set_task_state(current,state)

进程上下文是指当内核代表某个用户进程执行某个操作时,就称其处于进程上下文中。


进程树

获取当前进程的父进程的代码如下:

struct task_struct *my_parent = current->parent;

遍历一个进程的子进程的代码如下:

struct task_struct *task;

struct list_head *list;

list_for_each(list,¤t->children) {

task= list_entry(list, struct task_struct, sibling);

/*task now points to one of current’s children */

}

初如任务进程的描述符静态分配为init_task。如下代码永远成功:

struct task_struct *task;

for(task = current; task != &init_task; task = task->parent)

;

/*task now points to init */

获取任务列表中的下一个任务的代码如下:

list_entry(task->tasks.next,struct task_struct, tasks)

获取任务列表中的前一个任务代码如下:

list_entry(task->tasks.prev,struct task_struct, tasks)

上述代码段分别对应宏next_task(task)prev_task(task)

for_each_process(task),遍历整个任务列表,在每次迭代中,task指向列表中的下一个任务:

struct task_struct *task;

for_each_process(task){

/*this pointlessly prints the name and PID of each task */

printk(“%s[%d]\n”,task->comm, task->pid);

}

创建线程

创建线程采用的系统调用:

clone(CLONE_VM| CLONE_FS | CLONE_FILES | CLONE_SIGHAND, 0);

普通fork()调用:

clone(SIGCHLD,0);

vfork()调用:

clone(CLONE_VFORK| CLONE_VM | SIGCHLD, 0);


Flag

Meaning

CLONE_FILES

Parentand child share open files.

CLONE_FS

Parentand child share filesystem information.

CLONE_IDLETASK

SetPID to zero (used only by the idle tasks).

CLONE_NEWNS

Createa new namespace for the child.

CLONE_PARENT

Childis to have same parent as its parent.

CLONE_PTRACE

Continuetracing child.

CLONE_SETTID

Writethe TID back to user-space.

CLONE_SETTLS

Createa new TLS for the child.

CLONE_SIGHAND

Parentand child share signal handlers and blocked signals.

CLONE_SYSVSEM

Parentand child share System V SEM_UNDO semantics.

CLONE_THREAD

Parentand child are in the same thread group.

CLONE_VFORK

vfork()was used and the parent will sleep until the child


wakesit.

CLONE_UNTRACED

Donot let the tracing process force CLONE_PTRACE on the


child.

CLONE_STOP

Startprocess in the TASK_STOPPED state.

CLONE_SETTLS

Createa new TLS (thread-local storage) for the child.

CLONE_CHILD_CLEARTID

Clearthe TID in the child.

CLONE_CHILD_SETTID

Setthe TID in the child.

CLONE_PARENT_SETTID

Setthe TID in the parent.

CLONE_VM

Parentand child share address space.



你可能感兴趣的:(Linux内核研究)