为什么我的C代码中的pipe()一直返回-1

时间:2017-05-19 00:36:33

标签: c pipe

我认为应该是一个相当简单的问题,但无论出于何种原因,我似乎无法理解。在我试图编写的代码中,我的意图是创建一个子进程,该进程发送一个指向父进程的指针。指针是我自己定义的结构。然后父进程打印出其中一个字段。

我用gdb确定它是管道的返回(pipe_id); call是-1 - 我的代码退出的原因。我不确定为什么会这样。有什么想法吗?

/*
    -- Includes
*/
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>


/*
    -- Definitions
*/
#define BUF_SIZE  100
#define COMMAND_MESSAGE 1
#define MESSAGE_SIZE (sizeof(int)) * (20 * sizeof(char))


struct Msg {
   int message_type;
   char message[20];
};


int main() {
    /*
    * Local vars
    */

    /* Declare a handle for a pipe */
    int pid;
    /* Declare a handle to reference pipe ID */
    int pipe_id[2];
    /* Declare a return value for pipe init */  
    int ret;
    /* Define a buffer to store information */
    char buff[BUF_SIZE];    
    /*
    * Computation
    */
    /* Init the pipe */
    ret = pipe(pipe_id);
    if(ret = -1) {
        perror("pipe");
        exit(-1);
    }
    /* Create a new process -- this will simulate transmission to test
        out the INGEST code.. 
    */
    pid = fork();

    if (pid == 0) {
        /* 
            Description:
            Create a child process to simulate sending data to the parent.
        */
        printf("Simulator execute.\n");
        /* Declare a MsgId */
        struct Msg m;
        /* Define attributes for message */
        m.message_type = COMMAND_MESSAGE;
        int count = 0;
        strcpy(m.message,"Extract from Pool");
        /* Write to one end of the pipe */
        write(pipe_id[1],&m, MESSAGE_SIZE);
        /* Exit when necessary */
        while(true) {
            if(count = 1000000) {
                exit(0);
            }
        }
    }

    else {

        /* 
            Description:
            The parent process handles messages that it receives from 
            the child.
        */

        /* Define a handle for a received message */
        printf("Receiver execute.\n");
        struct Msg *received_m;
        /* Define the exit flag */
        read(pipe_id[0],received_m,MESSAGE_SIZE);
        printf("%d\n",received_m->message_type);
        exit(0);
    }   

}  

1 个答案:

答案 0 :(得分:2)

  if(ret = -1) {
        perror("pipe");
        exit(-1);
    }

您需要if(ret == -1)因为if (ret = -1)被视为始终为真。更确切地说:

  

赋值求值为已分配的值,任何非零值求值为&#34; true&#34;在布尔上下文中