[英]fgets in this program
我正在尝试在UNIX中制作一个C程序,其中父进程生成两个子进程。 父母将从stdin中读取数据并将其发送给他的孩子。 第一个孩子将在屏幕上显示从父亲那里读取的文本,并输出到标准输出中。 第二个孩子将在文件中显示读取的数据。 当父母输入“退出”时,他将向孩子发送终止信号并退出。
所以这是我做的完整代码,但是需要帮助的地方是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);
}
pipe
是OS /更低级别的pipe
,为您提供了UNIX文件描述符( int
)。 fgets
是libstdc /更高级别,并使用FILE*
。 您可以从文件低级样式中读取(读取OS函数),也可以使用fdopen
为descrTub1[0]
获取FILE*
。
fgets
函数需要一个指向FILE
的指针,而您要给它一个文件描述符,它是一个int
。
您可以使用fdopen
函数从文件描述符中获取FILE
指针:
FILE *fp = fdopen(descrTub1[0], "r");
并在对fgets
的调用中使用它:
fgets(bufferLectura,255,fp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.