1 #include <unistd.h> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <fcntl.h> 5 #include <error.h> 6 #include <errno.h> 7 int glob = 6; 8 char buf[] = "a write to stdout\n"; 9 10 int main (int argc, char **argv) 11 { 12 int var; 13 pid_t pid; 14 var = 88; 15 if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1) { 16 perror("write"); 17 } 18 19 if ((pid = fork()) < 0) { 20 perror("fork"); 21 } else if(pid == 0){ 22 glob++; 23 var++; 24 //printf("child: glob:%d var:%d\n",glob, var); 25 }else { 26 sleep(2); 27 } 28 29 printf("pid:%d,which parent id:%d\n",getpid(), getppid()); 30 printf("pid:%d glob:%d var:%d\n",getpid() ,glob, var); 31 return 0; 32 }
fork once call, twice return
output:
a write to stdout
pid:23354,which parent id:23320
pid:23354 glob:7 var:89
pid:23320,which parent id:23317
pid:23320 glob:6 var:88
时间: 2024-12-17 21:30:49