管道,分支,execl:错误的文件描述符

时间:2017-03-31 22:46:14

标签: c linux

目标是创建一个执行" first"和"第二"命令为first | second,但是我得到了错误的文件描述符错误。我已经在stackoverflow上阅读了关于构建管道的方法的不同主题,我尝试在这里使用与文件描述符向量相同的逻辑,但没有结果。你能帮我理解哪个是错误的吗? 我的观点:

#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

/* error message with exit */
void err (const char msg[])
{
    printf ("%s", msg);
    exit (-1);
}

#define BASH "/bin/bash"

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

    /* variables */
    pid_t pid;
    FILE *fp;
    char *token, *buffer;
    char first[128], second[128];
    int sz;

    int pfd[2];
    int read_fd = pfd[0];
    int write_fd = pfd[1];

    if (argc != 2)
        err ("Invalid number of args");

    /* open file and copy content in a buffer */
    fp = fopen (argv[1], "r+");

    /* find end of file, get size, rewind */
    fseek (fp, 0, SEEK_END);
    sz = ftell (fp);
    fseek (fp, 0, SEEK_SET);

    /* allocate enough space */
    buffer = (char *) malloc (sizeof (char) * (sz));
    fread (buffer, 1, sz, fp);
    buffer[sz] = '\0';

    /* parse  commands strings
    *
    * first line
    */
    token = strtok (buffer, "\n");
    strcpy (first, token);

    /* second line */
    token = strtok (NULL, "\n");
    strcpy (second, token);
    printf ("%s", second);

    fclose (fp);

    /* pipe, fork and execute with exec */
    pipe (pfd);

    pid = fork ();
    if (pid == 0) {
        //child
        close (read_fd);
        dup2 (write_fd, STDOUT_FILENO);
        close (write_fd);
        execl (BASH, BASH, "-c", first, (char *) NULL);
    } 
    else {
        wait (5);
        //parent
        close (write_fd);
        dup2 (read_fd, STDIN_FILENO);
        close (read_fd);
        execl (BASH, BASH, "-c", second, (char *) NULL);
    }
}

0 个答案:

没有答案