进程

来源:互联网 发布:logo设计软件app 编辑:程序博客网 时间:2024/06/06 23:55

概念
Linux系统是一个多进程的系统,它的进程之间具有并行性、互不干扰等特点。
也就是说,每个进程都是一个独立的运行单位,拥有各自的权利和责任。其中,各个进程都运行在独立的虚拟地址空间,因此,即使一个进程发生异常,它也不会影响到系统中的其他进程。

进程的ID

#include <sys/types.h> #include <unistd.h>pid_t getpid(void)      //获取本进程ID。pid_t getppid(void)       // 获取父进程ID

进程的创建
1)fork
功能:创建子进程
函数原型:pid_t fork(void)
头文件:#include <unistd.h>
返回值:

0: 子进程
子进程ID(大于0):父进程
-1: 出错

2)vfork
作用:建立一个新的进程
函数原型:’pid_t vfork(void)
头文件:

#include <sys/types.h>#include <unistd.h>

返回值:

0: 子进程
子进程ID(大于0):父进程
-1: 出错

fork()和vfork()的区别

  1. fork:子进程拷贝父进程的数据段
    vfork:子进程与父进程共享数据段
  2. fork:父、子进程的执行次序不确定
    vfork:子进程先运行,父进程后运行

程序比较:
fork:

#include <unistd.h>#include <stdio.h>int main(void){       pid_t pid;        int count=0;        pid = fork();        count++;        printf( “count = %d\n", count );        return 0;}

执行结果:
count = 1
count = 1

vfork:

#include <unistd.h>#include <stdio.h>int main(void){    pid_t pid;    int count=0;    pid = vfork();    count++;      printf( “count = %d\n", count );        return 0;}

执行结果:
count=1
count=2

0 0