【发布时间】:2019-01-05 15:37:05
【问题描述】:
这是我的整个代码:
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <unistd.h>
4. #include <sys/wait.h>
5. #include <string.h>
6. int main(int argc, char *argv[]) {
7. int p[2]; // p[0]: file descriptor for read end of pipe
8. // p[1]: file descriptor for write end of pipe
9. if (pipe(p) < 0) exit(1);
10. int rc1 = fork();
11. if (rc1 < 0){ fprintf(stderr, "fork error\n"); }
12. else if (rc1 == 0){ write(p[1], "1st child output",
13. sizeof("1st child output")); }
14. else{
15. int rc2 = fork();
16. if (rc2 < 0){ fprintf(stderr, "fork error\n"); }
17. else if (rc2 == 0){
18. printf("2st child output\n");
19. char *_1st_child_out;
20. read(p[0], _1st_child_out, sizeof("1st child output"));
21. strcat(_1st_child_out, ", AFTER PIPE YA FOOL");
22. printf("%s\n", _1st_child_out);
23. }
24. }
25. }
如果我初始化 19:13:
char *_1st_child_out;
带有 '\0' 或 NULL, 字符串保持为空,22:13:
printf("%s\n", _1st_child_out);
什么都不打印,那么 strcat() 和 read() 是如何工作的呢? 我不应该在调用它们之前插入任何空终止符吗? 垃圾值呢?
【问题讨论】:
-
read(p[0], _1st_child_out, sizeof("1st child output"))正在读入一个无效的未初始化指针。 -
它从 p[0] 中提供的文件描述符读取输入(在 pipe() 调用中写入),并存储已读取的内容(即在 write( ) 到 _1st_child_out *char
-
我认为
pipe()和fork()调用不会改变任何东西——你能用更小的程序重现错误吗? -
@AhmedRehan:
_1st_child_out是一个未初始化的指针。您无法将任何内容读入它所指向的内容。 -
@Blacksilver 作为当前的代码,没有任何错误,如果我将未初始化的字符指针“_1st_child_out”设为 NULL,则不会在其中写入或连接任何内容,我不是完全掌握管道、写入和读取的效果我不确定是哪个导致错误,无论如何我想知道两者如何处理这种情况