[英]C Unix program without warnings still not working
我想知道是否有人可以帮助我使用此代码(C Unix),因为我解决了所有警告,但是我的程序仍然无法正常工作……它既不创建.txt,也不要求我介绍文本。一切都按正确的顺序/正确吗? 怎么了? 非常感谢您的帮助。 抱歉,因为它是西班牙语。
#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("%s\n", bufferLectura);
}
}
void ProcesoHijo2() {
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);
FILE*fp = fdopen(descrTub2[0], "r");
while(1) {
fgets(bufferLectura,255,fp);
descrFichero = open("salida.txt",O_APPEND|O_WRONLY, 0600);
write(descrFichero, bufferLectura, strlen(bufferLectura));
}
}
void ProcesoPadre() {
char bufferLectura[256];
close(2);
dup(descrTub1[1]);
printf("[Proceso padre]Introduce un texto, o exit para salir");//[Parent process]insert text or exit
fgets(bufferLectura, 255,stdin);
while(strcmp(bufferLectura, "exit\n")) {
fprintf(stderr,"%s/n", bufferLectura);
write(descrTub2[1], bufferLectura, strlen(bufferLectura));
printf("[Proceso padre] Introduce un texto, o exit para salir ");//[Parent process]insert text or exit
fgets(bufferLectura, 255,stdin);
}
kill(pidHijo1, SIGTERM);
kill(pidHijo2, SIGTERM);
}
您在ProcesoHijo2
的6行代码(不计算空行)中打开文件了三个不同的时间(以三种不同的模式):
descrFichero = open("salida.txt", O_CREAT|O_TRUNC, 0600); /* One */
descrFichero = open("salida.txt", O_RDWR | O_TRUNC, 0600); /* Two */
FILE*fp = fdopen(descrTub2[0], "r");
while(1) {
fgets(bufferLectura,255,fp);
descrFichero = open("salida.txt",O_APPEND|O_WRONLY, 0600); /* Three */
write(descrFichero, bufferLectura, strlen(bufferLectura));
}
第一个将其截断,第二个将其截断。 第三次,一次又一次地打开文件(每次通过while循环),即使您之前已经使用相同的文件描述符descrFichero
两次打开了该文件。
将第一个替换为类似的内容,然后删除其他两个调用以open
:
descrFichero = open("salida.txt", O_APPEND | O_TRUNC | O_RDWR, 0600);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.