IPC via named pipe: Difference between revisions

→‎{{header|C}}: +implementation
(→‎{{header|Ruby}}: The event loop now works, but the code is bad enough to want {{improve}}.)
(→‎{{header|C}}: +implementation)
Line 9:
* Read/write operations on pipes are generally [[wp:Blocking (computing)|blocking]]. Make your program responsive to both pipes, so that it won't block trying to read the "in" pipe while leaving another process hanging on the other end of "out" pipe indefinitely -- or vice versa. You probably need to either poll the pipes or use multi-threading.
* You may assume other processes using the pipes behave; specificially, your program may assume the process at the other end of a pipe will not unexpectedly break away before you finish reading or writing.
 
=={{header|C}}==
<lang c>#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
 
size_t tally = 0;
 
void* write_loop(void *a)
{
int fd;
char buf[32];
while (1) {
/* This will block current thread. On linux it won't block
the other thread (the reader). I'd be intereted in
knowing if it will block the whole process on some other
OS (*BSD?) */
fd = open("out", O_WRONLY);
write(fd, buf, snprintf(buf, 32, "%d\n", tally));
close(fd);
 
/* Give the reader a chance to go away. We yeild, OS signals
reader end of input, reader leaves. If a new reader comes
along while we sleep, it will block wait. */
usleep(10000);
}
}
 
void read_loop()
{
int fd;
size_t len;
char buf[PIPE_BUF];
while (1) {
fd = open("in", O_RDONLY);
while ((len = read(fd, buf, PIPE_BUF))) tally += len;
close(fd);
}
}
 
int main()
{
pthread_t pid;
 
/* haphazardly create the fifos. It's ok if the fifos already exist,
but things won't work out if the files exist but are not fifos;
if we don't have write permission; if we are on NFS; etc. Just
pretend it works. */
mkfifo("in", 0666);
mkfifo("out", 0666);
 
/* because of blocking on open O_WRONLY, can't select */
pthread_create(&pid, 0, write_loop, 0);
read_loop();
 
return 0;
}</lang>
 
=={{header|Ruby}}==
Anonymous user