为了验证fork的用法,自编代码为fork1.c
1 #include <sys/types.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 int main(int argc, char **argv) 7 { 8 pid_t pid; 9 char *message; 10 int n; 11 12 printf("fork program starting "); 13 pid = fork(); 14 switch(pid) 15 { 16 case -1: 17 perror("fork failed!"); 18 exit(1); 19 case 0: 20 message = "This is the child!"; 21 n = 5; 22 break; 23 defalut: 24 message = "This is the parent."; 25 n = 3; 26 break; 27 } 28 for(; n > 0; n--){ 29 puts(message); 30 sleep(1); 31 } 32 33 exit(0); 34 }
结果为:
fork program starting This is the child! nication ] This is the child! This is the child! This is the child! This is the child!
例程代码fork2.c为:
1 #include <sys/types.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 int main() 7 { 8 pid_t pid; 9 char *message; 10 int n; 11 12 printf("fork program starting "); 13 pid = fork(); 14 switch(pid) 15 { 16 case -1: 17 perror("fork failed"); 18 exit(1); 19 case 0: 20 message = "This is the child"; 21 n = 5; 22 break; 23 default: 24 message = "This is the parent"; 25 n = 3; 26 break; 27 } 28 29 for(; n > 0; n--) { 30 puts(message); 31 sleep(1); 32 } 33 exit(0); 34 }
结果为:
nication : chapter11/fork2 fork program starting This is the parent This is the child This is the parent This is the child This is the parent This is the child This is the child nication : chapter11/fork2 This is the child
开始以为是代码有什么黑科技,结果gdb调试发现代码中的n没有为3过,所以自然是有问题的,再后来是关键字拼写错误:
default被某人写成了defalut了,最雷人的居然是vim也给高亮了,什么鬼。
后来发现,错误的关键字vim刚开始没有高亮,只不过是加上:后被当成了标签,而标签的高亮颜色恰好被我设置成和关键字高亮的颜色是一样的,看来还是需要动态看下代码的,不能仅靠下意识的输入了。