Last active
November 27, 2017 22:02
-
-
Save tonywallace64/225822523f7255205a17ed2e59ea0996 to your computer and use it in GitHub Desktop.
Multithreaded erlang port drivers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* This is a skeleton to show how to make multithreaded erlang port drivers */ | |
| /* This programme requires erl_comm.c from the standard erlang distribution */ | |
| /* setup, shutdown and handle_port_messages are device specific */ | |
| /* setup is expected to open device file for reading */ | |
| #include <unistd.h> | |
| #include <stdlib.h> | |
| #include <stdio.h> | |
| #include <fcntl.h> | |
| #include <errno.h> | |
| #include <string.h> | |
| #include <pthread.h> /* pthread functions and data structures */ | |
| static pthread_mutex_t mtx_write_port = PTHREAD_MUTEX_INITIALIZER; | |
| int write_port(void *data, int Size) | |
| { | |
| /* write port has mutex to allows recv_thread and main_thread | |
| to both be able to write to the erlang port without interfering | |
| with each other */ | |
| pthread_mutex_lock(&mtx_write_port); | |
| write_cmd(1,data,Size); | |
| pthread_mutex_unlock(&mtx_write_port); | |
| } | |
| void recv_thread(t_state *state) | |
| { | |
| fd = state->fd; | |
| struct | |
| { | |
| char prefix[5]; | |
| struct DEVICE_MSG data; | |
| } event; | |
| strcpy(event.prefix,"dev"); | |
| /* note: need to put timeout on device read in otherwise shutdown_flag | |
| may not read if device is not responding */ | |
| while (shutdown_flag == 0) | |
| { | |
| if (read(fd, &event.data, sizeof(event.data))== sizeof(event.data) | |
| write_port(&event,sizeof(event)); | |
| else | |
| exit(INVALID_DEVICE_DATA); | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| char *filename = argv[1]; | |
| int shutdown_flag = 0; | |
| setup(&state,filename); | |
| pthread_t thread_id; | |
| pthread_create(&thread_id, NULL, recv_thread, (void*)&state); | |
| handle_port_messages(); | |
| shutdown_flag++; | |
| pthread_join(thread_id,NULL), | |
| cleanup(&state); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment