在抄代码过程中,出现了一个小失误,然后长见识了 哈哈哈哈!!!
程序测试了父子进程运行过程中是不是 子进程是父进程的副本 这样一个概念
这个程序包含了很多细节在里面。
- fork之后的先手是不知道的,可能是父进程,也可能是子进程,这取决于系统的调度算法。程序采用了简单的同步,让父进程等了2秒
- stlen 和sizeof 程序用了sizeof-1 避免将null字节输出 ===》 strlen计算是不包含null,但是sizeof是包含的
- write是不带缓冲的!!! ---》 这点没有看太懂。。。对,就是不带缓冲的,不是标准的IO库!!
细细品味,全是精华!!!
#include <stdio.h>
#include <unistd.h> //for fork getpid getppid
#include <stdlib.h> //for write
#include <sys/types.h> //for pid_t
int globvar =6;
char buf[]="a write to stdout";
int main()
{
int var;
pid_t pid;
var =88;
if( write(STDOUT_FILENO,buf,sizeof(buf)-1) != sizeof(buf)-1 )
{
perror("write error");
exit(-1);
}
printf("\nbefore fork!\n");
//if( pid = fork() < 0 )//
//-->bug : 先进行fork()<0 fork返回两次 一次返回0 一次返回大于0 所以为false(0)
//父子进程都进入了 pid==0 所以都进行了++ 所以结果值都是7 和 89
if( (pid=fork()) < 0 )
{
perror("fork error!");
exit(-1);
}
else if( pid == 0 )//子进程修改两个变量
{
printf("parent pid = %ld\n",(long)getppid());
++globvar;
++var;
}
else
{
printf("----------\n");
sleep(2);//暂停父进程
printf("**********\n");
}
printf("pid = %ld glob = %d var = %d\n",(long)getpid(),globvar,var);
exit(0);
}