首页 > 代码库 > 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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。