Linux系统编程-----进程fork()

来源:互联网 发布:西安淘宝网页制作设计 编辑:程序博客网 时间:2024/05/02 02:50

在开始之前,我们先来了解一些基本的概念:

1. 程序, 没有在运行的可执行文件   进程,  运行中的程序2. 进程调度的方法:按时间片轮转 先来先服务短时间优先按优先级别3. 进程的状态:     就绪   ->>   运行  ->> 等待运行 ->> 就绪 //时间片完了等待 ->> 就绪 //等待的条件完成了查看当前系统进程的状态 ps auxfstatus:D    Uninterruptible sleep (usually IO)R    Running or runnable (on run queue)S    Interruptible sleep (waiting for an event to complete)T    Stopped, either by a job control signal or because it is being traced.W    paging (not valid since the 2.6.xx kernel)X    dead (should never be seen)Z    Defunct ("zombie") process, terminated but not reaped by its parent.<    high-priority (not nice to other users)N    low-priority (nice to other users)L    has pages locked into memory (for real-time and custom IO)s    is a session leaderl    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)+    is in the foreground process group4. 父进程/子进程 , 让一个程序运行起来的进程就叫父进程, 被调用的进程叫子进程5. getpid //获取当前进程的进程号   getppid //获取当前进程的父进程号6. fork //创建一个子进程,创建出来的子进程是父进程的一个副本,除了进程号,父进程号不同。子进程从fork()后开始运行, 它得到的fork返回值为0父进程得到的返回值为子进程的进程号返回值为-1时, 创建失败
来看一个程序:
#include <stdio.h>#include <unistd.h>int main(void){pid_t  pid ; //printf("hello world \n");//从fork开始就已经产生子进程pid = fork();    //就已经产生新的4G空间,复制空间//创建出来的子进程是父进程的一个副本,除了进程号,父进程号和子进程号不同//printf("hello kitty\n");if(pid == 0){//子进程运行区printf("child  curpid:%d  parentpid:%d \n" , getpid() , getppid());return 0 ; }//父进程运行区printf("parent curpid:%d  parentpid:%d \n" , getpid() , getppid());return 0 ; }




0 0
原创粉丝点击