在C中管道坏描述符

时间:2015-11-18 02:29:18

标签: c pipe file-descriptor

我有一个使用管道的程序让两个文件相互读写。我知道pipe(f_des)会创建两个文件描述符f_des[0]f_des[1]。我也知道如果你用一个来读,另一个必须用来写。但是,当我使用f_des[1]来读取和f_des[0]来编写时,我收到了错误的文件描述符错误。当我切换它们时,代码可以工作。我只是想知道为什么会这样。谢谢你的帮助。

修改:我收到Write: Bad file descriptor错误,然后出现Segmentation fault (core dumped)错误。

/* Unnamed pipe pipe.c */ 
/* Usage:  pipe message_to_be_written.  Parent write a message to child */ 
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <string.h> 

void main(int argc, char *argv[]) 
{  
    int f_des[2]; // File descriptors
    static char message[BUFSIZ];  
    char buffer[MAX_CANON]; 
    char *c; 
    int i,k, n; 
    pid_t childpid; 
    if (argc !=2) { 
        printf ("\n Usage: %s message\n", *argv); 
        exit(1);
    } 
    /* generate pipe */ 
    if (pipe(f_des) == -1) { // f_des[0] and f_des[1] get the descriptors
        perror ("Pipe"); 
        exit(2); 
    } 
    switch (fork()) { // Create two processes one using f_des[0] and one using f_des[1] to read and write
        case -1:  
            perror ("Fork"); 
            exit(3); 
        default: /* In the parent */ 
            close(f_des[0]); //If I change this to f_des[1] and use f_des[0] in the if statement, it works.
            if (read(f_des[1], message, BUFSIZ) != -1) { //Reading message
                printf ("Message received by parent: *%s*\n", message); 
                fflush(stdout); 
            } 
            else {  // Error if read returns -1
                error ("Read"); 
                exit(4);
            } 
        break; 
        case 0:  /* In the child */ 
            close(f_des[1]); // If I change this to f_des[0] and use f_des[1] in the if statement, the code works.
            if (write(f_des[0], argv[1], strlen(argv[1])) != -1) { // Writing message
                printf ("Message sent by child:    [%s]\n", argv[1]);
                fflush(stdout);  
            } 
            else { // Error if write returns -1
                perror ("Write"); 
                exit(5); 
            } 
    } 
    exit(0); 
}

0 个答案:

没有答案