读书笔记之UNIX环境高级编程(8)

来源:互联网 发布:唱吧上传出现网络异常 编辑:程序博客网 时间:2024/06/07 02:30
进程控制
1._exit并不执行标准I/O缓冲的冲洗动作
2.vfork()不对复制父进程空间,而是共享在父进程中运行,vfork保证子进程先运行,在他调用exec或exit后父进程才运行
#include <signal.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <sys/stat.h>#include <string.h>#include <sys/sem.h>#include <fcntl.h>#include <semaphore.h>#include <pthread.h>int glob = 6;int main(int argc, char* argv[]){int var = 88;int pid = fork();if(pid < 0){exit(0);}if(pid == 0){++ var;++ glob;printf("child:%d,%d\n", var, glob);exit(0);}else{++ var;printf("father:%d,%d\n", var, glob);}wait(NULL);return 0;}

father:89,6

child:89,7

结果说明,父子进程不共享全局变量和局部变量,子进程执行的是写时复制

#include <signal.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <sys/stat.h>#include <string.h>#include <sys/sem.h>#include <fcntl.h>#include <semaphore.h>#include <pthread.h>int glob = 6;int main(int argc, char* argv[]){int var = 88;int pid = vfork();if(pid < 0){exit(0);}if(pid == 0){++ var;++ glob;sleep(1);printf("child:%d,%d\n", var, glob);exit(0);}else{++ var;++ glob;printf("father:%d,%d\n", var, glob);}wait(NULL);return 0;}
child:89,7
father:90,8

vfork的子进程与父进程共享地址空间

3.调用vfork的main函数要exit(0)退出,如果用return 会出现段错误,子进程return返回到他的调用处,返回信息保存在main栈帧中,父进程继续运行但堆栈内容已被修改,就会出现段错误

#include <signal.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <sys/stat.h>#include <string.h>#include <sys/sem.h>#include <fcntl.h>#include <semaphore.h>#include <pthread.h>int glob = 6;void sum(){int pid = vfork();if(pid < 0){exit(0);}if(pid == 0){++ glob;//sleep(1);printf("child:%d\n", glob);}else{++ glob;printf("father:%d\n", glob);}}int main(int argc, char* argv[]){int var = 88;sum();//int pid = vfork();return 0;}

child:7
father:8
a.out: cxa_atexit.c:100: __new_exitfn: Assertion `l != ((void *)0)' failed.
Aborted (core dumped)

0 0
原创粉丝点击