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);
}