我在从管道读取数据时遇到了一些问题。不完全是。我读得很好,只是输出被弄乱了。
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int pfd[2];
int main(void)
{
pid_t pid;
int status;
char readbuf[1024];
int bytes_read = 0;
pipe(pfd);
switch((pid = fork())) {
case -1:
perror("fork");
break;
case 0:
/* child */
close(pfd[0]);
dup2(pfd[1], 1); /* stdout */
/* mkdir -p /home/edgar/testdir */
chdir("/home/edgar/testdir");
/* for file in a b c d e f g h i j k l m n o p q r s t u v w x y z;
* do
* touch $file
* done
*/
execl("/bin/ls", "ls", "-l", (char *)NULL);
exit(1);
default:
/* parent */
close(pfd[1]);
dup2(pfd[0], 0);
pid = wait(&status);
/* get input back from ls */
while ((bytes_read = read(pfd[0], readbuf, sizeof readbuf) > 0)) {
fprintf(stdout, "%s\n", readbuf);
}
printf("child exit status: %d\n", WEXITSTATUS(status));
}
return 0;
}
这是一个 globed up 输出的例子:
笔记本电脑$./test1
-rw-r--r-- 1 edgar edgar 0 Jan 31 09:15 u
-rw-r--r-- 1 edgar edgar 0 Jan 31 09:15 v
-rw-r--r-- 1 埃德加·埃德加普
0 1 月 31 日 09:15 w -rw-r--r-- 1 edgar edgar 0 1 月 31 日 09:15 x
-rw-r--r-- 1 edgar edgar 0 Jan 31 09:15 y
-rw-r--r-- 1 edgar edgar 0 1 月 31 日 09:15 z
1 edgar edgar 0 1 月 31 日 09:15 d
-rw-r--r-- 1 edgar edgar 0 1 月 31 日 09:15 e
它从 a-v 读取很好,然后 w-z 很奇怪,然后从 d 重新开始。 为了便于阅读,我在上面添加了额外的换行符。
最佳答案
关于 C 中的字符串,需要记住的最重要的事情之一是什么?它们本应以 NUL
终止!
read
不会在您的字符串中添加 NUL
- 它处理原始数据 block ,因此您必须自己执行此操作。这也意味着您不能传入缓冲区的完整大小,因为您需要为要添加的 NUL
留出空间
while ((bytes_read = read(pfd[0], readbuf, sizeof(readbuf)-1) > 0)) {
readbuf[bytes_read]='\0';
fprintf(stdout, "%s\n", readbuf);
}
关于c - 从 c 中的管道读取并打印到标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48545889/