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. One program should send "Hi" and the other should receive it. Something like that.
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. One program should send "Hi" and the other should receive it. Something like that.
first, have program 1 write the string to stdout (as if you'd like it to appear in screen). then the second program should read a string from stdin, as if a user was typing from a keyboard. then you run:
program_1 | program_2
From Creating Pipes in C, this shows you how to fork a program to use a pipe. If you don't want to fork(), you can use named pipes.
In addition, you can get the effect of
prog1 | prog2
by sending output ofprog1
to stdout and reading fromstdin
inprog2
. You can also read stdin by opening a file named/dev/stdin
(but not sure of the portability of that).This answer might be helpful for a future Googler.
You can find an advanced two-way pipe call example here.
Here's a sample:
The important steps in this program are:
popen()
call which establishes the association between a child process and a pipe in the parent.fprintf()
call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.pclose()
call that closes the pipe and causes the child process to terminate.And read:
But, I think that
fcntl
can be a better solutionA regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.
A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the
mkfifo()
library function.Example
writer.c
reader.c
Note: Error checking was omitted from the above code for simplicity.