所以我有一个 mytee 程序(功能少得多)。尝试学习如何使用管道/子项/等
(1) 我做 pipe
(2) 创建文件
(3) fork
(4) parent做scanf获取文本
(5) 将文本发送到管道
(6) child接收并写入文件
-> #4 应该是一个循环,直到用户写入 '.'
-> #6 应该继续写新行,但某处出现故障。
一些我认为可能是:
1. 我的权限有问题(但 O_APPEND 在那里,不确定我还需要什么)
2. parent do while 循环可能有问题,它应该将 msg 发送到管道 (fd[1])
3. #6 我强烈认为我的问题所在。初始写入后没有,继续写入。我不确定我是否需要以某种方式跟踪已写入的字节大小,但如果是这种情况,我希望最后一条消息不会出现在第一条消息上。
我现在很迷茫
我用
运行它 ./mytee test1
代码:
ret = pipe (fd);
if (ret == -1)
{
perror ("pipe");
return 1;
}
for (i=0;i<argc-1;i++) {
if ((filefd[i] = open(argv[i+1], O_CREAT|O_TRUNC|O_WRONLY|O_APPEND, 0644)) < 0) {
perror(argv[i]); /* open failed */
return 1;
}
}
pid = fork();
if (pid==0) /* child */
{
int read_data;
do {
read_data = read(fd[0], buffer, sizeof(buffer));
for(i=0;i<argc;i++) {
write(filefd[i], buffer, read_data);
}
} while (read_data > 1);
for (i=0; i<argc; i++)
close(filefd[i]);
return 0;
}
else { /* parent */
char msg[20];
do{
scanf("%s",msg);
write(fd[1],msg,sizeof(msg));
}while (strcmp(msg,".")!=0);
while ((pid = wait(&status)) != -1)
fprintf(stderr, "process %d exits with %d\n", pid, WEXITSTATUS(status));
return 0;
}
添加输出:
$ ./a.out test1
qwe
asd
zxc
.
^C
它没有正确退出。我认为 child 陷入了循环 以及test1的内容:
qwe
请您参考如下方法:
通过 OP 解决这个问题,据报道,问题是无条件写入所有 20 个字节的 msg
而不仅仅是其中包含的以 NUL 结尾的字符串。建议的最小修复:更改
scanf("%s",msg);
write(fd[1],msg,sizeof(msg));
到
scanf("%19s",msg);
write(fd[1],msg,strlen(msg));