Page MenuHomeFreeBSD

nmdmclosetest.c

Authored By
neel
Sep 27 2014, 12:13 AM
Size
1 KB
Referenced Files
None
Subscribers
None

nmdmclosetest.c

/* test nmdm fd close during read */
#include <sys/cdefs.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <pthread.h>
#include <pthread_np.h>
struct ttyfd {
int fd;
struct termios tio_orig, tio_new;
};
static void
ttyopen(struct ttyfd *tf)
{
tcgetattr(tf->fd, &tf->tio_orig);
tf->tio_new = tf->tio_orig;
cfmakeraw(&tf->tio_new);
tf->tio_new.c_cflag |= CLOCAL;
tcsetattr(tf->fd, TCSANOW, &tf->tio_new);
}
static void
make_blocking(int fd)
{
int i;
i = fcntl(fd, F_GETFL, 0);
if (i == -1) {
perror("Cannot fnctl");
exit(1);
}
i &= ~O_NONBLOCK;
if (fcntl(fd, F_SETFL, i) != 0) {
perror("Cannot set blocking");
exit(1);
}
}
static struct ttyfd tty_nmdm;
static void
do_server(void *arg)
{
volatile u_int *cookie;
int myid, blen;
char buf[1024];
cookie = (volatile u_int *)arg;
myid = pthread_getthreadid_np();
printf("thread%d starting ...\n", myid);
/*
* read(2) returns 0 to indicate end of file after the device has
* been revoked.
*/
*cookie = 1;
blen = read(tty_nmdm.fd, buf, 1024);
assert(blen == 0);
}
int
main(int argc, char *argv[])
{
volatile u_int cookie;
pthread_t thread;
if (argc < 2) {
printf("Missing /dev/nmdmX\n");
return (1);
}
tty_nmdm.fd = open(argv[1], O_RDWR | O_NONBLOCK);
if (tty_nmdm.fd < 0 || !isatty(tty_nmdm.fd)) {
printf("Cannot open file or not a tty\n");
return (1);
}
ttyopen(&tty_nmdm);
make_blocking(tty_nmdm.fd);
cookie = 0;
pthread_create(&thread, NULL, (void *)&do_server, (void *)&cookie);
while (cookie != 1)
;
/*
* Sleep before closing the 'fd' so is is very likely that the thread
* is blocked on the read().
*/
sleep(1);
close(tty_nmdm.fd);
printf("main thread closed nmdm fd\n");
pthread_join(thread, NULL);
printf("Done\n");
exit(0);
}

File Metadata

Mime Type
text/x-c
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
29284
Default Alt Text
nmdmclosetest.c (1 KB)

Event Timeline