- 论坛徽章:
- 0
|
下面这段代码原来自于LINUX源码情景分析,敲进去,修改了下代码中的错误,运行倒是成功。
可结果却有些奇怪。这是我在Redhat Linux9.0里面执行的结果,何故两次输出的结果是不同的?
Red Hat Linux release 9 (Shrike)
Kernel 2.4.20-8 on an i686
login: root
Password:
Last login: Fri Apr 6 15:48:14 from 192.168.0.10
You have new mail.
[root@wollt root]# cd devel
[root@wollt devel]# gcc pipe.c
[root@wollt devel]# ./a.out
63 Done!
[root@wollt devel]# /bin/ls -l pipe.c | /usr/bin/wc -c
64
[root@wollt devel]#
默地想起前次把代码中args2中的参数pipe.c去掉时,输出结果如下:
[root@wollt devel]# ./a.out
1027 Done!
[root@wollt devel]# ls -l | wc -c
1044
[root@wollt devel]# ls -l | wc -l
17
[root@wollt devel]#
发现规律没?每一行多一,即63+1=64以及1027+17=1044,这是何故,这两次执行差异在哪?想不明白。于是乎再试:
[root@wollt devel]# echo abc | wc -c
4
晕了,这哪门子理哟。
Appendix:
#include stdio.h>
int main()
{
int child_B, child_C;
int pipefds[2]; /* pipefds[0] for read, pipefds[1] for write */
char *args1[] = {"/usr/bin/wc", "-c", NULL};
char *args2[] = {"/bin/ls", "-l", "pipe.c", NULL};
/* process A */
pipe(pipefds); /* create a pipe */
if (!(child_B = fork())) /* for process B */
{
/**** Process B ****/
close(pipefds[1]); /* close the write end */
/* redirect stdin */
close(0);
dup2(pipefds[0], 0);
close(pipefds[0]);
/* ecec the target */
execve("/usr/bin/wc", args1, NULL); /* no return if success */
printf("pid %d: I am back, something is wrong!\n", getpid());
}
/* process A continues */
close(pipefds[0]); /* close the read end */
if(!(child_C = fork())) /* for process C */
{
/**** process C ****/
/* redirect stdout */
close(1);
dup2(pipefds[1], 1);
close(pipefds[1]);
/* exec the target */
execve("/bin/ls", args2, NULL); /* no return if success */
printf("pid %d: I am back, something is wrong!\n", getpid());
}
/* process A continues */
close(pipefds[1]); /* close the write end */
wait4(child_B, NULL, 0, NULL); /* wait for process B to finish */
printf("Done!\n");
return 0;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/34376/showart_272328.html |
|