fork问题

lq651659889 2013-02-21 10:01:26
1 #include <stdio.h>
2 #include <sys/wait.h>
3 #include <unistd.h>
4
5 #define MAXLINE 1024
6
7 int main(int argc, char** argv)
8 {
9 char buf[MAXLINE];
10 pid_t pid;
11 int status;
12
13 printf("%% ");
14 while(fgets(buf, MAXLINE, stdin) != NULL)
15 {
16 if(buf[strlen(buf) - 1] == '\n')
17 buf[strlen(buf) - 1] = '\0';
18 printf("buf is %s\n",buf);
19
20 if(pid = fork() < 0)
21 printf("the fork is worry!\n");
22 else if(pid == 0)
23 {
24 printf("the children run\n");
25 execlp(buf,buf, (char*)0);
26 printf("couldn't execute:%s,the pid is %d\n",buf, getpid());
27
28 }
29
30 if(pid = waitpid(pid, &status, 0) < 0)
31 printf("waitpid is error\n");
32
33 printf("%% ");
34 }
35
36 exit(0);
37 }
以上是源代码
这里是运行的结果
% ls
buf is ls
the children run
the children run
run run.c
run run.c
我想问为什么子进程会执行两次,而且父进程后面的都没有执行?
...全文
74 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
lq651659889 2013-02-22
  • 打赏
  • 举报
回复
没人看自己顶个!
quxiaojian8710 2013-02-22
  • 打赏
  • 举报
回复
典型的C语言代码编辑错误,代码中两条语句应该做如下修改: if(pid = fork() < 0) 修改为 if((pid = fork()) < 0) if(pid = waitpid(pid, &status, 0) < 0) 修改为 if((pid = waitpid(pid, &status, 0)) < 0) 建议在写makefile的时候添加-Wall和-Werror选项,在你的代码用如上选项进行编译时有如下Warning信息: cc1: warnings being treated as errors main.c: In function 'main': main.c:26: warning: suggest parentheses around assignment used as truth value main.c:37: warning: suggest parentheses around assignment used as truth value 编写规范严格的makefile可以避免很多低级错误。
nevil 2013-02-22
  • 打赏
  • 举报
回复
和exit无关,是你if少了括号,pid被强制赋了0
引用 3 楼 lq651659889 的回复:
引用 2 楼 zmlovelx 的回复:22 else if(pid == 0) 23 { 24 printf("the children run\n"); 25 execlp(buf,buf, (char*)0); 26 printf("couldn'……
nevil 2013-02-22
  • 打赏
  • 举报
回复
红色那句有问题,少了个括号 20if(pid = fork() < 0) 21 printf("the fork is worry!\n"); 22 else if(pid == 0) 23 { 应该是if((pid = fork()) < 0) 你的if里其实相当于强制给pid赋了一个值0, pid = ( fork() < 0),这种情况下, 父子进程都会进到else if(pid ==0)
lq651659889 2013-02-22
  • 打赏
  • 举报
回复
引用 2 楼 zmlovelx 的回复:
22 else if(pid == 0) 23 { 24 printf("the children run\n"); 25 execlp(buf,buf, (char*)0); 26 printf("couldn't execute:%s,the pi……
execlp后面的代码都没有执行,连printf都没有打印加这个有用么,本来是加了exit(127)的,输出结果还是一样的。
帅得不敢出门 2013-02-22
  • 打赏
  • 举报
回复
22 else if(pid == 0) 23 { 24 printf("the children run\n"); 25 execlp(buf,buf, (char*)0); 26 printf("couldn't execute:%s,the pid is %d\n",buf, getpid()); exit(0); // 加这个 27 28 }

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧