记一次粗心大意的代码错误

  为了验证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\n");
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\n");
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刚开始没有高亮,只不过是加上:后被当成了标签,而标签的高亮颜色恰好被我设置成和关键字高亮的颜色是一样的,看来还是需要动态看下代码的,不能仅靠下意识的输入了。

posted @   叕叒双又  阅读(98)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示