不知道为什么fgets之后会立即执行子进程
卦星 2013-01-28 11:10:07 这是比较简单程序代码,但是就是感觉输出结果有问题,希望有人帮忙解决一下
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(输出怎么直接在这一行输出了)
度娘没找到结果,不知道标准输入输出有什么具体的要求,请大神知道,是不是我的管道进程设置有错
新手没有积分,请见谅