Linux进程的创建
来源:互联网 发布:手机vpn软件 编辑:程序博客网 时间:2024/05/29 15:29
1、派生进程
要创建一个进程,最基本的系统调用为fork。系统调用fork用于派生一个进程,声明格式如下:
#include<unistd.h>
pid_t fork(void);
pid_t vfork(void);
调用fork时,系统将创建一个与当前进程相同的新的进程。它与原有的进程具有相同的数据、连接关系和在同一处执行的连续性。
派生子进程示例
#include<sys/type.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
pid_t pid;
if(pid=fork()<0)
{
printf("错误!!\n");
exit(1);
}
else if(pid==0)
{
printf("子进程!!\n");
}
else
{
printf("父进程!!\n");
}
exit(0);
}
调用fork函数与vfork函数的作用基本相同,但vfork并不完全复制父进程的数据段,而是和父进程共享数据段。vfork函数通常是与exec函数一起使用的,用来创建执行另一个程序的新进程。
调用vfoek函数时,父进程被挂起,子进程运行完exec函数族的函数或调用exit时解除父进程的挂起状态。
#include<sys/type.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
pid_t pid;
if(pid=vfork()<0)
{
printf("错误!!\n");
exit(1);
}
else if(pid==0)
{
printf("子进程!!\n");
}
else
{
printf("父进程!!\n");
}
exit(0);
}
这里的vfork创建与上述fork代码基本相同,但是其运行结果是不同的,fork创建的进程其运行结果是动态的,而vfork创建的进程其运行结果是固定的。
使用vfork,运行结果总是子进程先返回,因为在调用vfork时付进程挂起。
2、创建执行其他程序的进程————使用exec函数
#include<sys/types.h>#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
pid_t pid;
if((pid=vfork())<0)
{
printf("vfork error!\n");
exit(1);
}
else if(pid==0)
{
printf("child process PID:%d\n",getpid());
setenv("PS1","CHILD\\$",1);
printf("Process%4d:calling exec.\n",getpid());
if(execl("/bin/sh","/bin/sh","arg2",NULL)<0)
{
printf("Process%4d:execl error!\n",getpid());
exit(0);
}
}
printf("Process%4d:You should never see this because the child is already gone.\n",getpid());
printf("Process%4d:The child process is exiting!.\n");
}
else
{
printf("Parent process PID:%d.\n",getpid());
printf("Process%4d:The parent has fork process %d.\n",pid);
printf("Process%4d:The child has called exec or has exited.\n",getpid());
}
return 0;
}
3、Linux系统特有的调用_ _clone
#include<sched.h>
int _ _clone(int (*fn) (void *arg), void *child_stack,int flags,void *arg) ;
fn——函数指针,指向要执行的函数。
child_stdck——子进程堆栈段的指针。
flags——表示不同继承内容的标识。
flags标识的选取
CLONE_VM——继承父进程的虚拟存储器属性
CLONE_FS——继承父进程的chroot(根目录)、chdir(当前目录)、umask(权限掩码)
CLONE_FILES——继承父进程的文件描述符
CLONE_PID——继承父进程的文件锁、进程号及时间片
CLONE_SIGHAND—— 继承父进程的信号处理程序
- Linux进程的创建
- Linux进程的创建
- Linux进程的创建
- Linux进程的创建和进程树
- Linux进程管理之进程的创建
- Linux进程-进程的创建
- linux进程解析--进程的创建
- Linux进程管理之进程的创建
- linux进程创建(2)进程的继承
- Linux下进程的创建
- linux 进程链的创建
- linux守护进程的创建
- linux 新进程的创建
- 【Linux】进程的创建fork()
- linux下的进程创建
- Linux下进程的创建
- Linux的进程------进程的描述和进程的创建
- 【linux 编程】linux/unix 进程的创建
- Records
- 轻松学习JavaScript七:JavaScript的流程控制语句
- 蓝桥杯OJ刷题日记——02-基础练习 01字串
- C++学习笔记31——类的基础概念
- java web中几个概念的区别
- Linux进程的创建
- 基于struts2的文件上传
- 数据迁移后的迁移结果比对方法
- STM32 RTC 读写不正确
- Regex: 0.正则表达式初探
- VS连接MySQL·:Unable to connect to any of the specified MySQL hosts(VS连接MySQL出错)
- hdu 计算机学院大学生程序设计竞赛(2015’11)搬砖
- java用户角色权限数据库设计
- kettle学习:JsonInput使用