c - C 中两个程序之间的管道

标签 c piping execl

在过去的几个小时里,我一直被困在两个程序之间的管道工作上,而且我被困住了,不确定我是否做错了什么。我的程序的想法是,我将使用interface.c打开一个管道,然后执行db.c。我想使用两个管道在两个不同的程序之间进行通信。现在,interface.c 是“父级”,db.c 是“子级”,我不确定是否通过 execl 命令将参数正确传递到管道。一切都正确编译,但是当我尝试运行接口(interface)程序时,我收到一条错误消息:“文件号错误”。是否有可能是我没有正确使用管道?目前,我只是想让我的程序通过管道将整数值发送到 db.c。任何帮助将不胜感激。

接口(interface).c的代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>
//PIPES:
//
//Parent: reads from P1_READ, writes on P1_WRITE
//Child:  reads from P2_READ, writes on P2_WRITE
#define P1_READ     0
#define P2_WRITE    1
#define P2_READ     2
#define P1_WRITE    3

// the total number of pipe *pairs* we need
#define NUM_PIPES   2

int main(int argc, char *argv[])
{
    //Create Pipe Array
    int fd[2*NUM_PIPES];

    //For Parameter Passing:
    char param0[20];        //P1_Read
    char param1[20];        //P2_Write
    char param2[20];        //P2_Read
    char param3[20];        //P1_Write

    snprintf(param0, sizeof(param0), "%d" , fd[0]);
    snprintf(param1, sizeof(param1), "%d" , fd[1]);
    snprintf(param2, sizeof(param2), "%d" , fd[2]);
    snprintf(param3, sizeof(param3), "%d" , fd[3]);

    //Variables
    pid_t pid;
    int val = 42;

    //Allocate the PIPES
    for (int i=0; i<NUM_PIPES; ++i)
    {
        if(pipe(fd+(i*2)) < 0)
        {
            perror("Failed to allocate the pipes");
            exit(EXIT_FAILURE);
        }
    }

     //If the fork of the program does not work:
    if ((pid = fork()) < 0)
    {
        perror("Failed to fork process");
        return EXIT_FAILURE;
    }



    if(pid == 0)
    {   //Child Process
        execl("./db", "db", param0, param1, param2, param3, (char *)NULL);
    }
    else
    {   //Parent Process

        //SENDING VALUES HERE
        close(fd[P2_READ]);
        close(fd[P2_WRITE]);
        printf("Interface is sending|%d| to DB\n", val);
        if(write(fd[P1_WRITE],&val, sizeof(val)) != sizeof(val))
        {
            perror("Interfae failed to send value to DB");
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}

这是用于 db.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/types.h>
//Typedef-Class-
typedef struct Information
{
    int accountId;
    int checkNumber;
    int date;
    float amount;
} Information;

int main(int argc, char *argv[])
{
//For Input
    //Account Data
    Information acctData[25];
    int dataStorageLooper = 0;      //How many db entries

    //For File Input
    int aVal;
    int bVal;
    int cVal;
    float dVal;

    //Prepare for file input:
    FILE * fp;
    fp = fopen ("accountData.txt", "r");

    //Reads Input
    while(1)
    {
        if (fscanf(fp, "%d %d %d %f", &aVal, &bVal, &cVal, &dVal)!=4)
        {
            break;
        }
        //Puts data into appropriate arrays
        acctData[dataStorageLooper].accountId= aVal;
        acctData[dataStorageLooper].checkNumber= bVal;
        acctData[dataStorageLooper].date= cVal;
        acctData[dataStorageLooper].amount= dVal;
        dataStorageLooper++;
    }

    //Decrement index to point to last item
    dataStorageLooper--;

    //Displays all values
    printf("\nDisplaying AccountData.txt\n");
    for( int i = 0; i < dataStorageLooper; i++)
    {
        printf("Line|%d|: Account|%d|: Check|%d|: Date|%d|: Amount|%.2f|\n",i,acctData[i].accountId,acctData[i].checkNumber,acctData[i].date,acctData[i].amount);
    }
    //Closes File
    fclose(fp);
//End Input

//Parameter Receiving:
    int pipes[4];           //Pipe Array
    int value = 7;
    int test;

    //Build the pipes
    pipes[0] = atoi(argv[1]);       //P1_Read
    pipes[1] = atoi(argv[2]);       //P2_Write
    pipes[2] = atoi(argv[3]);       //P2_Read
    pipes[3] = atoi(argv[4]);       //P1_Write

    //Troubleshooting    
    printf("The number of parameters: %d\n",argc);
    printf("Parameter 1: %s\n", argv[0]);
    printf("I stared correctly\n");

    //Testing
    close(pipes[0]);
    close(pipes[3]);

    //SHOULD RECEIVE VALUE HERE
    test = read(pipes[2], &value, sizeof(value));

        if (test < 0)
        {
            perror("DB: Failed to read data from parent");
            exit(EXIT_FAILURE);
        }
        else if (test == 0)
        {
            //Unexpected
            fprintf(stderr, "DB: Read End-Of-File from pipe");
        }
        else
        {
            //What did the child receive?
            printf("DB: Received Value:(%d)\n", value);
        }
        close(pipes[2]);
        close(pipes[1]);




    return 0;
}

最佳答案

您做错的事情之一是在为 fd 中的各个元素分配任何值之前对其进行 snprintf 操作。这是未定义的行为,并且您作为参数传递的值完全没有意义(充其量)。

不过,我觉得这是一种非常奇怪的做事方式。通常你只会 dup2 fds 0 和 1,以便子级的 stdin 和 stdout 被重定向到适当的管道 fds。

关于c - C 中两个程序之间的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822729/

相关文章:

c - 使用 fscanf 读取复杂格式字符串

c++ - scanf(%s) EOF 问题

bash - 恢复上一个屏幕(如果有)

c - Execlp 与 Execl

c - 如何使用execle()为/bin/login传递环境变量?

c - 使用指针赋值/正常赋值之间的区别?

c - 菜鸟 void 指针混淆

R - 运行管道运算符(operator)的 t 检验

c - 将两个程序通过管道连接在一起 C Linux

c - C 中的父/子和管道,子-父通信