首页 > 代码库 > Linux多进程(fork)

Linux多进程(fork)

进程概念:
一个进程是一次程序执行的过程,它和程序不同,程序是静态的,它是一些保存在磁盘上可执行的代码和数据的集合,而进程是一个动态概念,也是操作系统分配资源的最小单位

fork和exec是两个重要的系统调用,fork的作用是根据现有的进程复制出一个新的进程,原来的进程称为父进程,新的进程成为子进程,
系统中运行着很多进程,这些进程都是从开始的一个进程一个一个复制出来的。


#include <sys/type.h>
#include <unistd.h>
pid_t fork(void);

fork调用失败返回-1,调用成功在父子进程中的返回值不一样,子进程中返回0,父进程中返回的数值大于0

 

#include <sys/types.h> //基本系统数据类型的头文件
#include <unistd.h> //包含了许多UNIX系统服务的函数原型 getpid函数
#include <stdio.h> //输入输出函数

int main(void){
    pid_t pid;
    char * message;
    int n;
    pid = fork();
    if(pid < 0){
        perror("fork failed");
    }
    if(pid == 0){
        n = 6;//父子进程变量n互不影响
        message = "This is the child my pid is";
    }else{
        n = 3;////父子进程变量n互不影响
        message = "This is the parent my pid is";
    }
    for(; n > 0; n--){
        printf("%s %d\n", message, getpid());
        sleep(1);
    }
    return 0;
}

 

Linux多进程(fork)