0

我需要以下程序的帮助,它应该 fork() 两个孩子,child1 应该发送两个随机数,在一个用空格分隔的字符串中,到 child2 槽管道,等待 1 秒然后再做一次,直到它收到来自父母的 SIGUSR1 (父母在 5 秒后发送)。child2 应该运行“main.exe”二进制文件,将管道的输出重定向到 main.exe 的输入,并将 main.exe 的输出重定向到 out.txt 文件。main.exe 二进制文件本身就可以正常工作,它位于应用程序文件夹中。

这是学校的作业。我已经设法使用写入和读取功能将字符串从 child1 发送到 child2。但是部分作业是每次我重定向输出或输入时,我必须使用 dup(int a, int b) 函数。我也应该让 child1 接受?使用 sigaction 的 SIGUSR1,(当收到孩子 1 应该在 stderr 上打印 'TERMINATED' 并终止)-> 我不知道该怎么做。该程序成功完成但似乎没有做任何事情,child1 中的 printf 部分似乎无法按我的预期工作。任何帮助将不胜感激。

#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;
}
4

0 回答 0