我正在尝试完成一个可以派生函数子进程的程序,而父进程可以获取输入文件(在同一目录下),反转该文件的内容,然后使用管道函数传递给子进程。 Child将从管道中读取消息并生成输出文件。我已完成fork,创建管道和反向功能。但是我不得不把它写到管道上。我知道当我尝试将参数传递给写入函数时,必定存在一些类型混淆,任何命中都会受到赞赏。
这是我到目前为止的代码:
#include <stdio.h>
#include <stdlib.h> //exit
#include <string.h>
#include <sys/types.h> //pid_t
#define READ_END 0
#define WRITE_END 1
int main(int argc, char *argv[]){
long loc;
FILE *in, *out;
char ch;
if (argc != 3)
{
printf("Usage %s message\n", argv[0]);
exit(EXIT_FAILURE);
}
int pipefd[2];
int pipe_return = pipe(pipefd);
if((in = fopen(argv[1], "rb")) == NULL) {
printf("Cannot open input file.\n");
exit(1);
}
if((out = fopen(argv[2], "wb"))==NULL) {
printf("Cannot open output file.\n");
exit(1);
}
if(pipe_return == -1)
{
printf("Unable to create pipe\n");
exit(EXIT_FAILURE);
}
pid_t return_from_fork = fork();
if (return_from_fork == -1)
{
printf("Unable to fork\n");
exit(EXIT_FAILURE);
}
else if (return_from_fork == 0) //this is a child
{
char msg;
close(pipefd[WRITE_END]);
int read_return = read(pipefd[READ_END], &msg, 1);
printf("read return:%d\n", read_return);
while(read_return > 0){
fputc(ch, out);
printf("%c",msg);
read_return = read(pipefd[READ_END], &msg, 1);
}
printf("child ends\n");
close(pipefd[READ_END]);
exit(EXIT_SUCCESS);
}
else if (return_from_fork > 0)
{
close(pipefd[READ_END]);
printf("this is parent\n");
fseek(in, 0L, SEEK_END);
loc = ftell(in);
while(loc >= 0L){
fseek(in, loc, SEEK_SET);
ch = fgetc(in);
printf("%c",ch);
int write_r = write(pipefd[WRITE_END], ch, 1);//here is the problem the printf() return -1
printf("%d",write_r);
loc--;
}
printf("\n");
close(pipefd[WRITE_END]);
wait(NULL);
printf("file successful generated.\n");
fcloseall();
exit(EXIT_SUCCESS);
}
}
以下是编译结果:
zzz@ubuntu:~/Desktop/test$ gcc filereversecopy.c -o run
zzz@ubuntu:~/Desktop/test$ ./run src.txt out.txt
this is parent
�-1
-1e-1c-1n-1e-1t-1n-1e-1s-1 -1a-1 -1s-1i-1 -1s-1i-1h-1T-1
read return:0
child ends
file successful generated.
zzz@ubuntu:~/Desktop/test$
答案 0 :(得分:1)
你说的就是问题,你要传递ch来写,而ch是char类型。我相信你的意思是&amp; ch。我打赌如果你改变那个写将返回1而不是-1。
此外,你寻求到最后开始阅读,但当你寻求到最后,你指的是EOF。您需要在EOF之前的位置开始阅读。所以在“fseek(in,0L,SEEK_END); loc = ftell(in);”之后添加“loc--; fseek(in,loc,SEEK_SET);”让它发挥作用。