首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

不知道为何fgets之后会立即执行子进程

2013-02-24 
不知道为什么fgets之后会立即执行子进程这是比较简单程序代码,但是就是感觉输出结果有问题,希望有人帮忙解

不知道为什么fgets之后会立即执行子进程
  这是比较简单程序代码,但是就是感觉输出结果有问题,希望有人帮忙解决一下
1 #include<stdio.h>
  2 #include<string.h>
  3 #include<stdlib.h>
  4 #include<sys/types.h>
  5 #include<unistd.h>
  6 #include<sys/stat.h>
  7 int main()
  8 {
  9     pid_t pid;
 10     int pipe_fd[2];
 11     char buf[100];
 12     int num;
 13     memset(buf,0,100);
 14     if(pipe(pipe_fd)<0)
 15     {
 16         printf("creat pipe error;\n");
 17         exit(0);
 18     }
 19     if((pid=fork())==0)
 20     {
 21         sleep(1);
 22         waitpid(pid,NULL,0);
 23         close(pipe_fd[1]);
 24         printf("now we will read the file\n");
 25         num=read(pipe_fd[0],buf,sizeof(buf));
 26         if(num!=1)
 27         {
 28             printf("read file is :%s\n",buf);
 29         }
 30         else
 31         {
 32             printf("read error\n");
 33             exit(0);
 34         }
 35         exit(0);
 36     }
 37     else
 38     {
 39         close(pipe_fd[0]);
 40         printf("now we will write some files\n");
 41         printf("please input:");
 42         fgets(buf,100,stdin);
 43         printf("\n");
 44         num=write(pipe_fd[1],buf,100);
 45         if(num!=-1)
 46             printf("write good %s\n",buf);
 47         else
 48             {
 49                 printf("error");
 50                 exit(0);
 51             }
 52         exit(0);


 53     }
 54 }
下面是输出的结果
[……@localhost new]$ ./2
now we will write some files
please input:now we will read the file(这儿为什么直接跳到了子进程)
asd(这是输入的)

write good asd

[……@localhost new]$ read file is :asd(输出怎么直接在这一行输出了)
度娘没找到结果,不知道标准输入输出有什么具体的要求,请大神知道,是不是我的管道进程设置有错
新手没有积分,请见谅 C,fgets, 标准输入输出
[解决办法]
父进程已经退出了,所以命令提示符出来了。但是子进程还在运行(sleep中),所以会在命令提示符出来以后再打印输出。程序本身运行是正确的。
[解决办法]
你这代码写的, 仔细看下吧
(1)   fork  该怎么用?
      pid = fork() ==  0   这个判断, 说明if 是子进程
      else  分支里的代码才是父进程
(2)   你在子进程中 wait 一个pid = 0 的进程?


查下手册看看api怎么用, 不难吧?
[解决办法]


if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
execlp(buf, buf, (char *)0);
err_ret("couldn't execute: %s", buf);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");

热点排行