Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Last active March 3, 2020 07:14
Show Gist options
  • Save moriyoshi/c7556c376e0ee47d1825328c8024cccd to your computer and use it in GitHub Desktop.
Save moriyoshi/c7556c376e0ee47d1825328c8024cccd to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
static pthread_t thr;
static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER;
#define print(s) write(2, s, sizeof(s) - 1);
void handler(int sig)
{
print("HEY\n");
}
void *fn(void *arg)
{
char buf[1];
print("thread started\n");
pthread_mutex_lock(&mtx2);
pthread_cond_signal(&cond1);
for (;;) {
if (read(0, buf, sizeof(buf)) < 0) {
if (errno == EINVAL) {
break;
}
}
print("read\n");
}
}
int main()
{
{
struct sigaction act = {
.sa_handler = handler,
.sa_mask = SIGINT | SIGTERM,
.sa_flags = SA_RESTART,
};
sigaction(SIGINT, &act, NULL);
}
pthread_create(&thr, NULL, fn, NULL);
pthread_mutex_lock(&mtx1);
pthread_cond_wait(&cond1, &mtx1);
pthread_mutex_unlock(&mtx1);
pthread_mutex_lock(&mtx2);
}
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
static pthread_t thr;
static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER;
#define print(s) write(2, s, sizeof(s) - 1);
void handler(int sig)
{
print("HEY\n");
}
void *fn(void *arg)
{
int s = *(int *)arg;
char buf[1];
print("thread started\n");
pthread_mutex_lock(&mtx2);
pthread_cond_signal(&cond1);
for (;;) {
if (read(s, buf, sizeof(buf)) < 0) {
if (errno == EINVAL) {
break;
}
}
print("read\n");
}
}
int main()
{
{
struct sigaction act = {
.sa_handler = handler,
.sa_mask = SIGINT | SIGTERM,
.sa_flags = SA_RESTART,
};
sigaction(SIGINT, &act, NULL);
}
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s < 0) {
perror("oops");
return 1;
}
{
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(12346),
.sin_addr = htonl(0x7f000001),
};
if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("oops");
return 1;
}
}
pthread_create(&thr, NULL, fn, &s);
pthread_mutex_lock(&mtx1);
pthread_cond_wait(&cond1, &mtx1);
pthread_mutex_unlock(&mtx1);
pthread_mutex_lock(&mtx2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment