C - 使用dup将stdout重定向到execl(二进制文件)的输入

时间:2017-04-13 12:34:16

标签: c pipe dup execl sigaction

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

这是学校的家庭作业。我设法使用write和read函数将child1中的字符串发送到child2。但是,部分功课是每次我重定向输出或输入时,我必须使用dup(int a,int b)函数。 我也应该让child1?接受? SIGUSR1使用sigaction,(当收到孩子1时,应该打印' TERMINATED'在stderr上并终止) - >我不知道该怎么做。该程序成功完成但似乎没有做任何事情,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;
}

0 个答案:

没有答案