Corrupt text file

2

Good afternoon, I'm doing a practice for the university, the program consists of the creation of a loop in which a child process, created by fork () sends a pid to the father through a pipe and then dies, The parent then enters the pid and a line break in a text file.

The number of times you execute the loop and the name of the text file you enter as arguments to the function.

The problem is that the program I think works well but at the time of creating the text file it encodes it in such a way that it is impossible for me to read the results. I leave the code below. Thanks in advance.

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>

int main(int argc, char *argv[]){

 int pid, fd[2], estado;
 int buf[256];
 creat(argv[2], 7777);
 //printf("%d\n", f);

 pipe(fd);

 int nhijos = *argv[1] -'0';
 for(int i=0; i<nhijos; i++){
     switch(fork()){
     case 0:        //Hijo
        close (fd[0]);
        close (1);
        dup(fd[1]);
        close(fd[1]);
        pid = getpid();
        buf[1]= pid;
        write(1, buf, 2);
        write(1, "\n", 1);
        exit(0);
    case -1: 
        printf("fork");
    default:        //Padre
        close (fd[1]);
        close (0);
        dup(fd[0]);
        close(fd[0]);
        read(0, buf, 3);
        write(3, buf, 3);
        int err;
        err = wait(&estado);
    }
}
printf("Termino la ejecucion \n");
exit(0);
}
    
asked by Cesar Martin Genova 18.01.2017 в 19:21
source

1 answer

2

Without testing your code, I see what you do

int buf[256];
. . .
write( 1, buf, 2 );
write( 1, "\n", 1 );

Doing that, write( ) would be printing the binary representation of a number, not the characters (digits) that form it. Also, where do you find that the size of a int is 2 ? In any case, it could be write( 1, buf, sizeof( int ) ); .

Among the various possible solutions, I propose to convert those int to caracteres , and print the latter. I show you a functional example, easy to adapt to your code:

#include <stdio.h>
#include <string.h>

int Number = 1024;
char string[15]; // Núm. arbitrario; caracteres máximos.
sprintf( string, "%d", Number ); // string[] = "1024\n";

write( 1, string, strlen( string ) );
write( 1, "\n", 1 );

You are free to use it wherever you want; or you send the correct characters to the father, or you send the number and the father transforms it. To the taste of the consumer.

    
answered by 18.01.2017 / 20:01
source