use semaphore to remove race con in tests

Signed-off-by: Aidan Hahn <aidan@aidanis.online>
This commit is contained in:
Aidan Hahn 2022-03-06 23:39:55 -08:00
parent 033f1d5173
commit 8dca2bac04
No known key found for this signature in database
GPG key ID: 327711E983899316
2 changed files with 23 additions and 7 deletions

View file

@ -4,14 +4,24 @@
#include <sys/types.h> #include <sys/types.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <semaphore.h>
#include <fcntl.h>
int out_fd[2]; int out_fd[2];
int err_fd[2]; int err_fd[2];
const char *out_message = "standard message"; const char *out_message = "standard message";
const char *err_message = "error message"; const char *err_message = "error message";
const char *sem_name = "/alog_testing_sem";
int main() { int main() {
// RPC sync mechanism. Start locked
sem_t *sem = sem_open(sem_name, O_CREAT, 0x777, 0);
if (sem_unlink(sem_name)) {
perror("couldnt unlink semaphore");
// might as well proceed since it is a leak anyways
}
// make RPC pipe // make RPC pipe
pipe(out_fd); pipe(out_fd);
pipe(err_fd); pipe(err_fd);
@ -23,7 +33,9 @@ int main() {
pid_t childpid; pid_t childpid;
if ((childpid = fork()) == -1) { if ((childpid = fork()) == -1) {
perror("fork fail"); perror("cannot fork");
sem_close(sem);
deinit_alog();
return 1; return 1;
} }
@ -40,14 +52,18 @@ int main() {
alog(ERROR, err_message); alog(ERROR, err_message);
alog(PRINT, out_message); alog(PRINT, out_message);
exit(0); if (sem_post(sem)) {
perror("cannot increment semaphore");
return 1;
}
// parent process // parent process
} else { } else {
// we can do checks from here // we can do checks from here
char out_read_buffer[128] = {0}; char out_read_buffer[128] = {0};
char err_read_buffer[128] = {0}; char err_read_buffer[128] = {0};
if (sem_wait(sem)) {
usleep(10); perror("cannot decrement semaphore");
}
read(err_fd[0], err_read_buffer, 128); read(err_fd[0], err_read_buffer, 128);
// cant check read len because of timestamp // cant check read len because of timestamp
@ -75,8 +91,8 @@ int main() {
printf("out and err log printing are successfull.\n"); printf("out and err log printing are successfull.\n");
sem_close(sem);
deinit_alog();
} }
deinit_alog();
return 0; return 0;
} }

View file

@ -3,7 +3,7 @@ ALOG_TESTS = $(ALOG_TEST_SRCS:.c=)
$(ALOG_TESTS): $(ALOG_LIB) $(ALOG_TESTS): $(ALOG_LIB)
$(CC) $(CFLAGS) -g -o $(BUILD_DIR)/$@.o -c tests/$@.c $(CC) $(CFLAGS) -g -o $(BUILD_DIR)/$@.o -c tests/$@.c
$(CC) -o $(TARGET_DIR)/$@ $(BUILD_DIR)/$@.o $(ALOG_LIB) $(CC) -o $(TARGET_DIR)/$@ $(BUILD_DIR)/$@.o $(ALOG_LIB) -lpthread
chmod +x $(TARGET_DIR)/$@ chmod +x $(TARGET_DIR)/$@
alog-tests: $(ALOG_TESTS) alog-tests: $(ALOG_TESTS)