Exampel code for pipe
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include "ucore/iomux.h"
|
||||
|
||||
|
||||
|
||||
void in_cb(struct IOMux *mux, struct IOMuxFD *fd, unsigned int event)
|
||||
{
|
||||
|
||||
char buf[16];
|
||||
ssize_t rc;
|
||||
|
||||
rc = read(fd->fd, buf, sizeof buf);
|
||||
printf("Read returned %ld\n", (long)rc);
|
||||
if (rc <= 0) {
|
||||
if (rc == -1 && errno == EAGAIN) {
|
||||
return;
|
||||
} else if (rc == -1) {
|
||||
perror("read");
|
||||
}
|
||||
return;
|
||||
}
|
||||
iomux_unregister_fd(mux, fd);
|
||||
close(fd->fd);
|
||||
|
||||
}
|
||||
|
||||
void out_cb(struct IOMux *mux, struct IOMuxFD *fd, unsigned int event)
|
||||
{
|
||||
char str[] = "hello";
|
||||
ssize_t rc;
|
||||
|
||||
rc = write(fd->fd, str, strlen(str));
|
||||
printf("write returned %ld\n", (long)rc);
|
||||
if (rc <= 0) {
|
||||
if (rc == -1 && errno == EAGAIN) {
|
||||
return;
|
||||
} else {
|
||||
perror("write");
|
||||
}
|
||||
iomux_unregister_fd(mux, fd);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
int pipes[2];
|
||||
pipe(pipes);
|
||||
uc_set_nonblocking(pipes[0]);
|
||||
uc_set_nonblocking(pipes[1]);
|
||||
|
||||
struct IOMuxFD rfd= {
|
||||
.fd = pipes[0],
|
||||
.what = MUX_EV_READ,
|
||||
.callback = in_cb,
|
||||
};
|
||||
|
||||
struct IOMuxFD wfd= {
|
||||
.fd = pipes[1],
|
||||
.what = MUX_EV_WRITE,
|
||||
.callback = out_cb,
|
||||
};
|
||||
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
|
||||
struct IOMux *mux = iomux_create(IOMUX_TYPE_SELECT);
|
||||
iomux_register_fd(mux, &rfd);
|
||||
iomux_register_fd(mux, &wfd);
|
||||
|
||||
iomux_run(mux);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user