Search code examples
cpipeforkexecl

How to send continuous stream of data from one process to another via EXECL


I am writing C program which constantly generates two string values named stateName and timer (with the rate of five times per second). I need to concatenate and pass them to another process called ProcessNo3_TEST which is responsible for tokenizing and also displaying them.

The problem is I don't know how to pass them continuously via execl. I had a couple of attempts but none of them were successful. Here is my code which works fine for a single pair of values (e.g. UP2 and 98):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define READ 0
#define WRITE 1

int FIFO[2];
char fileDescriptor[10];

char* stringMaker( char *s1,char *s2 );

int main()
{
    char lengthInChar[15],msg[200];
    int msgLength,i;
    char *stateName, *timer;
    if (pipe(FIFO) == -1)
    {
        printf("cannot create pipe\n");
        exit(1);
    }
    sprintf(fileDescriptor, "%d", FIFO[READ]);

    stateName = "UP2";              // for instance
    timer = "98";                   // for instance

    msgLength = strlen(stateName) + strlen(timer) +3;
    strcpy(msg, stringMaker(stateName, timer) );
    write(FIFO[WRITE], msg, msgLength);

    switch (fork())
    {
    case 0:
        sprintf(lengthInChar, "%d", msgLength);
        execl("ProcessNo3_TEST", "ProcessNo3_TEST", lengthInChar, fileDescriptor, NULL);
        exit(1);
    case -1:
        perror("fork() failed-->");
        exit(2);
    default:
        break;
    }
    sleep(10);
    exit(0);
}

char* stringMaker( char *s1,char *s2 )
{
    char *s3;
    strcpy(s3,s1);
    strcat(s3,"-");
    strcat(s3,s2);
    strcat(s3,"-");
    strcat(s3,"\0");
    return s3;
}

Can anyone help on this please?

(I am running CygWin on Windows by the way)

----------UPDATE-------------

As advised in comments below, I found a good example of fdopen() which solved my problem. (Link)


Solution

  • Although one can arrange to pass one pipe end's file descriptor number (in string form) as a program argument, normally one would instead redirect the child process's standard streams to read from (in this case) or write to the pipe. This is usually achieved via dup2(), which you would apply in the child process, after forking but before execl().

    Parent and child processes then communicate via the pipe. In this case, the parent writes to the writing end and the child reads from the reading end. Either or both can wrap their file descriptor in a stream by passing it to fdopen(). Then you can use stdio functions with it. Note, too, that after the fork, each process should close the FD for the pipe end it does not intend to use.