没有警告的 C Unix 程序仍然无法运行

标签 c

我想知道是否有人可以帮助我处理这段代码 (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);

关于没有警告的 C Unix 程序仍然无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8263822/

相关文章:

c - C 的最终 CRC

c - 如何与玩家和 AI 交替移动

c - 如何在 C 中创建一个用新数组替换数组的函数

c - 使用冒泡排序在 C 中对二维数组进行排序

c - 二进制搜索递归无法正常运行

c - (->)箭头运算符在c中做什么?

c - 动态内存分配的流行用法

c - 服务器编程错误

c - 如何将四个 16 位 uint 编码为 64 位 uint,然后再次解码它们?

c - 使用定义填充结构数组