Skip to content

Instantly share code, notes, and snippets.

@mrjohannchang
Created October 4, 2013 02:39
Show Gist options
  • Save mrjohannchang/6820188 to your computer and use it in GitHub Desktop.
Save mrjohannchang/6820188 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <unistd.h>
int main() {
FILE * f1 = fopen("output1.txt", "a");
FILE * f2 = fopen("output2.txt", "a");
char buf[4] = {0};
flock(fileno(f1), LOCK_EX);
printf("File 1 has been locked by us.\n");
sleep(10);
flock(fileno(f2), LOCK_EX);
printf("File 2 has been locked by us.\n");
for (int i = 0; i < 10;) {
sprintf(buf, "a%d\n", i++);
fwrite(buf, sizeof(buf), 1, f1); fflush(f1);
fwrite(buf, sizeof(buf), 1, f2); fflush(f2);
if (i > 9) i = 0;
sleep(1);
}
flock(fileno(f1), LOCK_UN);
flock(fileno(f2), LOCK_UN);
fclose(f1);
fclose(f2);
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <unistd.h>
int main() {
FILE * f2 = fopen("output2.txt", "a");
FILE * f1 = fopen("output1.txt", "a");
char buf[4] = {0};
flock(fileno(f2), LOCK_EX);
printf("File 2 has been locked by us.\n");
sleep(10);
flock(fileno(f1), LOCK_EX);
printf("File 1 has been locked by us.\n");
for (int i = 0; i < 10;) {
sprintf(buf, "b%d\n", i++);
fwrite(buf, sizeof(buf), 1, f2); fflush(f2);
fwrite(buf, sizeof(buf), 1, f1); fflush(f1);
if (i > 9) i = 0;
sleep(1);
}
flock(fileno(f2), LOCK_UN);
flock(fileno(f1), LOCK_UN);
fclose(f2);
fclose(f1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment