尝试对文件求和并通过 pipe/fork/process 传输时出错?
Error when trying to sum a file and transfer through pipe/fork/process?
我试图在这个程序中将信息从子进程传递到父进程。这是到目前为止的代码,仍在清理它:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
main() {
char *s, buf[1024];
int fds[2];
int sum;
s = "Hello world!\n";
FILE *file;
pipe(fds);
if(fork()==0){
printf("child process: \n");
int c;
int number;
sum = 0;
file = fopen("file1.dat", "r");
if (file) {
while ((c = getc(file)) != EOF){
sum+=c;
printf("child process: step 1");
fclose(file);
}
}
write(fds[1],&sum,12);
exit(0);
}
read(fds[0],buf,12);
write(1,buf,strlen(s));
}
它编译正确且没有错误,但是当我 运行 它时 return 是数字 6 后面跟着一堆无法识别的字符(问号)。
我可能遗漏了什么?我的感官通过阅读告诉我一些事情。
编辑:我应该补充一点,我的目的是让子进程打开并读取文件(其中包含多行数字)并将它们相加,然后 return 将总和交给父进程。
假设 sizeof(int) == 4
,您写入了 12 个任意字节(其中 4 个表示 int
值 sum
- 其他 8 个字节给出未定义的行为,因为它们不是'the same array' 作为 sum
) 放到管道上,然后将它们读入 buf
。然后您尝试使用 write()
.
将任意字节打印到标准输出
您不检查任何错误;你应该。
您确实需要将字节转换回 ASCII 数字流才能理解值。你应该用write(fds[1], &sum, sizeof(sum))
写,read(fds[0], &sum, sizeof(sum))
读,然后你可以用printf("%d\n", sum);
打印。或者您可以自己进行转换并仍然使用 write()
打印转换后的字符串。或者您可以将 sum
转换为 child 中的一串数字。或者……
我试图在这个程序中将信息从子进程传递到父进程。这是到目前为止的代码,仍在清理它:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
main() {
char *s, buf[1024];
int fds[2];
int sum;
s = "Hello world!\n";
FILE *file;
pipe(fds);
if(fork()==0){
printf("child process: \n");
int c;
int number;
sum = 0;
file = fopen("file1.dat", "r");
if (file) {
while ((c = getc(file)) != EOF){
sum+=c;
printf("child process: step 1");
fclose(file);
}
}
write(fds[1],&sum,12);
exit(0);
}
read(fds[0],buf,12);
write(1,buf,strlen(s));
}
它编译正确且没有错误,但是当我 运行 它时 return 是数字 6 后面跟着一堆无法识别的字符(问号)。
我可能遗漏了什么?我的感官通过阅读告诉我一些事情。
编辑:我应该补充一点,我的目的是让子进程打开并读取文件(其中包含多行数字)并将它们相加,然后 return 将总和交给父进程。
假设 sizeof(int) == 4
,您写入了 12 个任意字节(其中 4 个表示 int
值 sum
- 其他 8 个字节给出未定义的行为,因为它们不是'the same array' 作为 sum
) 放到管道上,然后将它们读入 buf
。然后您尝试使用 write()
.
您不检查任何错误;你应该。
您确实需要将字节转换回 ASCII 数字流才能理解值。你应该用write(fds[1], &sum, sizeof(sum))
写,read(fds[0], &sum, sizeof(sum))
读,然后你可以用printf("%d\n", sum);
打印。或者您可以自己进行转换并仍然使用 write()
打印转换后的字符串。或者您可以将 sum
转换为 child 中的一串数字。或者……