您的位置:首页 > 大数据 > 人工智能

基于Sendmail配置完整功能的邮件服务器----视频下载

2010-03-27 16:41 543 查看
fork
基本知识热身:
每个进程都有自己的ID号码,调度进程的ID为0,init进程的ID为1。fork函数用于创建一个子进程。
1.子进程复制父进程的数据空间,堆,栈


#include<stdio.h>


#include<stdlib.h>


#include<string.h>


#include<fcntl.h>


#include<sys/types.h>


#include<unistd.h>


#include<sys/wait.h>




int glob = 6; //heap



int main(void)


{


int var; //stack


pid_t pid;


var = 88;


printf("before fork\n"); /* we don't flush stdout */




if ((pid = fork()) < 0)
{


err_sys("fork error");


}
else if (pid == 0)
{ /* child */


glob++; /* modify variables */


var++;


}
else
{


sleep(2); /* parent */


}


printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);


exit(0);


}

注明:
1.这段代码在终端的输出如下:
before fork
pid = 430, glob = 7, var = 89
pid = 429, glob = 6, var = 88
可见,子进程改写的是自己的数据空间,并不对父进程的数据空间造成影响
2.如果把这段代码改为文件输出,将会有两行before fork,因为子进程把标准输出缓冲的数据空间也复制了一份,只不过我们连接终端时,标准输出是行缓冲的,换行符洗刷了一次,而连接文件时,标准输出是全缓冲的,所以输出两行
2.文件共享
子进程复制父进程的文件描述符,而和父进程共享文件偏移量


#include<stdio.h>


#include<stdlib.h>


#include<string.h>


#include<fcntl.h>


#include<sys/types.h>


#include<unistd.h>


#include<sys/wait.h>




int main()


{


char result[3];


//FILE *fp = NULL;


int file_handle;


pid_t pc;


int readnum=0;


//fp = fopen("/home/nsl/myprogram/testfork.txt","rw");


file_handle = open("/home/nsl/myprogram/testfork.txt",O_RDWR);


pc=fork();


if(pc<0)


{


printf("error fork\n");


exit(1);


}


else if(pc>0)


{


sleep(3);


//readnum=fread(result,1,1,fp);


readnum = read(file_handle,result,1);


printf("readnum=%d\n",readnum);


result[1]='\0';


printf("11111111111111=%s\n",result);


exit(0);


}


else if(pc==0)


{


//readnum=fread(result,2,1,fp);


readnum = read(file_handle,result,2);


printf("readnum=%d\n",readnum);


result[2]='\0';


printf("222222222222=%s\n",result);


}
fclose(fp);
close(file_handle);


return 0;


}
注明:
1.父子进程谁先执行,并无定论,随系统而定,一般认为为抢占式
2.如果子进程读了一个字符,那么父进程再读,则是文件的下一个字符,可见他们是共享文件偏移量
3.open是系统调用,fopen是库函数,并且fopen是文件缓冲的,一般认为fopen是open的一个高级封装,打开设备文件,肯定是用open,打开普通文件,可以考虑用fopen,可是这里用fopen只能读到一次,再去读的话,读不出来,具体原因不知道
4.sizeof和strlen的区别:sizeof是个运算符,在程序编译的时出结果,strlen是函数,程序运行的时候出结果,如果对于一个字符串常量什么的,能用sizeof,就用sizeof,因为程序运行的时候会快点本文出自 “nnssll” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐