Created
October 4, 2013 02:39
-
-
Save mrjohannchang/6820188 to your computer and use it in GitHub Desktop.
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
#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); | |
} |
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
#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