#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main(void){
pid_t pid = fork();
if(!pid){
printf("the id of Children is %d\n",getpid());
printf("the id of Parents is %d\n",getppid());
exit(0);
}
printf("the id of Children is %d\n",pid);
printf("the id of Parents is %d\n",getpid());
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int a;
int b = 10;
int main(void)
{
pid_t pid = fork();
int c = 20;
int *p = (int *)malloc(4);
*p = 30;
if(!pid){
a = 100;
b = 100;
c = 100;
*p = 100;
printf("a = %d b = %d c = %d *p = %d\n",a,b,c,*p);
exit(0);
}
printf("a = %d b = %d c = %d *p = %d\n",a,b,c,*p);
return 0;
}
调用fork后 后面的代码父子进程都会执行一次,但是因为变量在不同的区域,父子进程只会公用代码区的数据,其他区例如全局区,bss区,堆区,栈区,子进程只会复制父进程。但是存储的空间子进程和父进程是两个独立的部分
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main(void){
int fd = open("a.txt",O_RDWR|O_CREAT|O_TRUNC,0666);
pid_t pid = fork();
if (!pid){
sleep(1);
write(fd,"abc",3);
close(fd);
exit(0);
}
write(fd,"123",3);
close(fd);
return 0;
}
父子进程共享一个文件表,使用同一个文件指针
打出的结果是
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main(void){
pid_t pid = fork();
int fd = open("a.txt",O_RDWR|O_CREAT,0666);
if (!pid){
sleep(1);
write(fd,"abc",3);
close(fd);
exit(0);
}
write(fd,"1234",4);
close(fd);
return 0;
}
open被父子进程调用了两次,打开了两个文件表,导致会发生重写覆盖的效果