I need help with the following program, It's supposed to fork() two childs, child1 should send two random numbers, in a string separated by space, to child2 trough pipe, wait 1 sec and do it again until it receives SIGUSR1 from the parent(parent sends it after 5 secs). child2 should run 'main.exe' binary file, redirect the pipe's output to main.exe's input and redirect main.exe's output to out.txt file. The main.exe binary works just fine by itself and it's in the application folder.
It's a school homework. I've managed to send strings from the child1 to child2 using write and read functions. But part of the homework is that each time i'm redirecting outputs or inputs, i must use the dup(int a, int b) function. Also im supposed to make child1 ?accept? the SIGUSR1 using sigaction,(when it is received child 1 should print 'TERMINATED' on stderr and terminate) -> i dont know how to do that. The program completes successfully but doesn't seem to do anything, the printf part in child1 seems to not work as i intended. Any help would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int fd[2];
pipe(fd);
pid_t pid1 = fork();
struct timespec tim1, tim5;
tim1.tv_sec = 1;
tim1.tv_nsec=0;
tim5.tv_sec = 5;
tim5.tv_nsec=0;
if (pid1 > 0) {
pid_t pid2 = fork();
if (pid2 > 0) {
close(fd[0]);
close(fd[1]);
nanosleep(&tim5, (struct timespec *) NULL);
kill(pid1, SIGUSR1);
int status;
wait(&status);
} else if (!pid2) {
execl("main.exe","main", (char*) 0);
close(fd[1]);
char *buf;
if((buf = malloc(23))==NULL){
return 3;
}
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
int file = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, mode);
ssize_t bytesread;
while ((bytesread=read(fd[0], buf, 22)) > 0) {
buf[bytesread] = '\0';
printf("%s\n", buf);
}
//^redirect pipe output to the main.exe's input and then redirect main.exe's output to out.txt text file^
} else {
return 2;
}
} else if (!pid1) {
close(fd[0]);
int a, b;
dup2(fd[1], STDOUT_FILENO);
while (1) {//child 1 should write to stderr "TERMINATED" if SIGUSR1 is received, and terminate
a = rand();
b = rand();
printf("%d %d\n", a, b);
nanosleep(&tim1, (struct timespec *) NULL);
}
} else {
return 1;
}
return 0;
}