fork_vfork.c
来自「主要测试fork和vfork区别的代码 比较简单」· C语言 代码 · 共 38 行
C
38 行
/*fork.c*/
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int global=22;
char buf[]="the test content!\n";
int main(void)
{ int test=66;
pid_t pid;
if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1)
perror("write error!");
printf(" fork test!\n");
/* fork */
pid = fork(); /*we should check the error*/
// pid =v fork(); /*we should check the error*/
if(pid == -1){
perror("fork");
exit;
}
/*if the pid=0 then it is the child*/
else if(pid == 0){
printf("global=%d test%d Child,my PID is %d\n",global,test,getpid());
global++;
test++;
// exit(0); //如果没有显式退出 会发生什么?
}
/*else be the parent*/
//else
//{sleep(2);}
sleep(2);
printf("global=%d test%d Parent,my PID is %d\n",global,test,getpid());
exit(0);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?