簡體   English   中英

沒有警告的C Unix程序仍然無法正常工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM