How to send a simple string between two programs using pipes?

后端 未结 7 1073
渐次进展
渐次进展 2020-11-22 12:17

I tried searching on the net, but there are hardly any resources. A small example would suffice.

EDIT I mean, two different C programs communicating with each other.

7条回答
  •  庸人自扰
    2020-11-22 12:31

    Here's a sample:

    int main()
    {
        char buff[1024] = {0};
        FILE* cvt;
        int status;
        /* Launch converter and open a pipe through which the parent will write to it */
        cvt = popen("converter", "w");
        if (!cvt)
        {
            printf("couldn't open a pipe; quitting\n");
            exit(1)
        }
        printf("enter Fahrenheit degrees: " );
        fgets(buff, sizeof (buff), stdin); /*read user's input */
        /* Send expression to converter for evaluation */
        fprintf(cvt, "%s\n", buff);
        fflush(cvt);
        /* Close pipe to converter and wait for it to exit */
        status=pclose(cvt);
        /* Check the exit status of pclose() */
        if (!WIFEXITED(status))
            printf("error on closing the pipe\n");
        return 0;
    }
    

    The important steps in this program are:

    1. The popen() call which establishes the association between a child process and a pipe in the parent.
    2. The fprintf() call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.
    3. The pclose() call that closes the pipe and causes the child process to terminate.

提交回复
热议问题