Created
November 17, 2017 08:42
-
-
Save grimmerk/d26e1dbff718170dc5861777974f69ad to your computer and use it in GitHub Desktop.
linux/unix use c to read file
This file contains 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 <error.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <time.h> | |
// forked process can use the file descriptor from parent's process without open again. Then two process can synchronize the file operations. | |
// ref: | |
// https://stackoverflow.com/questions/5284062/two-file-descriptors-to-same-file | |
// paragraph1: | |
// It depends on where you got the two file descriptors. If they come from a dup(2) call, | |
// then they share file offset and status, so doing a write(2) on one will affect the position on the other. | |
// If, on the other hand, they come from two separate open(2) calls, each will have their own file offset and status. | |
// paragraph2: | |
// This is guaranteed if they both refer to the same file description, aka you got them from "dup" or "dup2" (or inherited via fork()). | |
// paragraph3: | |
// when you use dup() or dup2() or fork() , the file table is shared by both of the file descriptors. so if you write something from one file descriptor , and again write something through other file descriptor , then it is appended not overwritten. | |
// ref2: | |
// https://stackoverflow.com/questions/42319310/is-a-file-descriptor-local-to-its-process-or-global-on-unix | |
// steps: | |
// build: cc test.c | |
// run: ./a.out | |
int main(int argc, const char *argv[]) | |
{ | |
//3 | |
int fd = open("test.txt", O_RDWR | O_CREAT, 0666); | |
if (fd == -1) { | |
printf("open fail"); | |
// perror("open file mytest"); | |
} | |
printf("open ok1:%d", fd); | |
printf("\n"); | |
//result: 4. different value than fd | |
// int fd2 = open("test.txt", O_RDWR | O_CREAT, 0666); | |
// if (fd2 == -1) { | |
// printf("open 2 fail"); | |
// // perror("open file mytest"); | |
// } | |
// printf("open ok2:%d", fd2); | |
// printf("\n"); | |
// if use another terminal to execute the compiled program, file descriptor is the same, 3 | |
// it seems normal and the oepration is independent although they have the same number. | |
while (1) { | |
sleep(1); | |
} | |
close(fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment