进程标识符:每个进程都有非负的整形表示唯一的进程ID。
进程的创建:
1)fork()创建一个新进程。子进程会得到父进程中数据段,栈段和堆区域的一份拷贝。子进程独立可以修改这些内存段。但是文本段是子进程和父进程共享的内存段,不能被子进程修改
fork()---进程一分为二《父进程-父进程(id!=0)、子进程(id==0),出错(id=-1)》
2)vfork()创建一个新进程,子进程会立即即调用exec,于是不会存访问该地址空间。相反在子进程调用exec或exit之前,它在父进程的空间中运行,会更改父进程的数据段、栈和堆。
vfork()---保证子进程先运行,在它调用exec或(exit)之后父进程才可能被调度运度运行。3)execve()创建一个新进程。系统调用会销毁所有的内存段去重新创建一个新的内存段,它需要一个可执行文件或者脚本作为参数。
execve()和fork()创建的进程都是运行进程的子进程。
1.fork(),父子进程谁新运行不定,由调度器决定。期望子进程先退出,父进程在子进程退出时读取子进程退出状态
<span style="font-size:14px;">#include<stdio .h >
#include<unistd .h >
int main1()
{
pid_t <strong>id=fork()</strong>;
int i =0;
for(;i <2;i ++) {
if(id ==0) {//child
printf( "child,pid:%d,ppid:%d\n", getpid(),getppid());
}else{//father
printf( "father,pid:%d,ppid:%d\n",getpid(),getppid());
sleep(1);
}
}
return 0;
}</span>
代码共享,数据私有,写时拷贝。父子进程各自i++
创建过程: i=0;父进程、子进程 i=1;父->子、子->子 i=2;退出,
2.fork()、文件描述符、文件指针、open、close、
文件描述符-系统调用接口提供;文件指针-C语言提供。
系统调用(open、write、close)在库函数(fopen、fwrite、fclose)的下层,库函数调用系统调用。
系统调用--不带缓冲,库函数--带缓冲。
int open (文件路径;怎样打开(只写,若不存在创建之 (读、写 ));权限)
</pre><pre name="code" class="cpp"><span style="font-size:14px;">#include<errno .h >
#include<sys /stat .h >
#include<sys /types .h >
#include<fcntl .h >
#include<string .h >
int main2()
{ const char * msg ="hello bit\n" ;
<strong>// fwrite(msg,1,strlen(msg),stdout); //FILE*
// write(1 ,msg,strlen(msg)); //fd</strong>
int fd =<strong>open( "./log",0_WRONLY| 0_CREAT,0644);</strong>
if(fd <0) {
printf( "open errror: %s\n",strerror(errno));
return -1;
}
//0、1 、2—— stdin、stdout 、stderr
printf("fd-> %d\n",fd); //fd->3
int count =5;
while(count --<0) {
write(fd,msg,strlen(msg));
}
<strong> close(fd);</strong>
return 0;
}</span>
3.fork()、write、fwrite
<span style="font-size:14px;">int main3()
{
<strong> write(1, "w-hello\n",6);//fd->system call
fwrite( "fw-world\n",1,6,stdout);//FILE* ->lib</strong>
pid_t id =fork();
int i =0;
if(id ==0) {//child
printf( "child,pid:%d,ppid:%d\n", getpid(),getppid()); }
else{//father
printf( "father,pid:%d,ppid:%d\n",getpid(),getppid()); sleep(1); }
return 0;
}</span>