我正在尝试在 UNIX 中编写一个 C 程序,其中父进程生成两个子进程。 父级将从标准输入读取数据并将其发送给其子级。 第一个 child 将在屏幕上显示从他父亲那里读到的文本到标准输出。 第二个子项将在文件中显示读取的数据。当父级输入“退出”时,他将向子级发送终止信号并退出。
这是我所做的完整代码,但我需要帮助的地方是 void ProcesoHijo2()
。当我必须编译时,我仍然有一个警告,这个:
74: warning: passing argument 3 of ‘fgets’ makes pointer from integer without a cast
/usr/include/stdio.h:624: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘int’ -->in
void ProcesoHijo2()
该程序是西类牙语的,所以变量名称也是如此,我希望这不会成为问题,你可以尽快帮助我,因为我很绝望......谢谢你!!!!
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
int pidHijo1;
int descrTub1[2];
int pidHijo2;
int descrTub2[2];
void ProcesoHijo1();
void ProcesoHijo2();
void ProcesoPadre();
int main(int argc, char *argv[]) {
pipe(descrTub1);
pipe(descrTub2);
pidHijo1 = fork();
if (pidHijo1 == 0) {
ProcesoHijo1();
return 0;
}
pidHijo2 = fork();
if (pidHijo2 == 0)
ProcesoHijo2();
else
ProcesoPadre();
}
void ProcesoHijo1() {
char bufferLectura[256];
close(0);
dup(descrTub1[0]);
while (1) {
fgets(bufferLectura, 255, stdin);
printf("%sn", bufferLectura);
}
}
void ProcesoHijo2() { //-->So here is where I have trouble to program...I don't know if it's just something from inside this process or from above...
char bufferLectura[256];
int descrFichero;
close(0);
dup(descrTub1[0]);
descrFichero = open("salida.txt", O_CREAT | O_TRUNC, 0600);
descrFichero = open("salida.txt", O_RDWR | O_TRUNC, 0600);//-->do I need this one?
while(1) {
fgets(bufferLectura,255,descrTub1[0]); //-->I have to read it from pipe and save it in bufferLectura, but I don't know how to put it...
write(descrFichero, bufferLectura, strlen(bufferLectura));
descrFichero = open("salida.txt", O_WRONLY|O_APPEND, 0600); //-->Is this correct?
}
}
void ProcesoPadre() {
char bufferLectura[256];
close(2);
dup(descrTub1[1]);
printf("[Proceso padre]Introduce un texto, o exit para salir");
fgets(bufferLectura, 255,stdin);
while(strcmp(bufferLectura, "exitn")) {
fprintf(stderr,"%s/n", bufferLectura);
write(descrTub2[1], bufferLectura, strlen(bufferLectura));
printf("[Proceso padre] Introduce un texto, o exit para salir ");
fgets(bufferLectura, 255,stdin);
}
kill(pidHijo1, SIGTERM);
kill(pidHijo2, SIGTERM);
}
最佳答案
函数fgets
需要一个指向FILE
的指针,而您给它一个int
的文件描述符。
您可以使用函数 fdopen
从文件描述符获取 FILE
指针:
FILE *fp = fdopen(descrTub1[0], "r");
并在调用 fgets
时使用它:
fgets(bufferLectura,255,fp);
关于c - 该程序中的 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8258748/