欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

板凳——————————————————c++(87)

程序员文章站 2022-06-23 22:10:31
#include #include #include #include #include #include #include #include int main(int argc, char* argv[]){//int main(int argc, char...

#include <fcntl.h>
#include <stdio.h>
#include <error.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include

int main(int argc, char* argv[]){
//int main(int argc, char ** argv){
struct flock lock;
int res1, fd1 = open(“Test.txt”, O_RDWR|O_CREAT, 0777);
if(fd1 > 0){
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = getpid();
res1 = fcntl(fd1, F_SETLK, &lock);
printf(“return value of fcntl = %d\n”, res1);
while(true)
;
}

////Linux C与C++ 一线开发p277
int fd2;
char mapped_mem2, * p2;
int flength2 = 1024;
void * start_addr2 = 0;
fd2 = open(argv[1], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
flength2 = lseek(fd2, 1, SEEK_END);
write(fd2, “\0”, 1);
lseek(fd2, 0, SEEK_SET);
mapped_mem2 = (char
) mmap(start_addr2,
flength2,
PROT_READ,
MAP_PRIVATE,
fd2,
0);
printf("%s\n", mapped_mem2);
close(fd2);
munmap(mapped_mem2, flength2);

////Linux C与C++ 一线开发p278
int fd3;
char *mapped_mem3, *p3;
int flength3 = 1024;
void * start_addr3 = 0;

fd3 = open(argv[1], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
flength3 = lseek(fd3, 1, SEEK_END);
write(fd3, "\0", 1);
lseek(fd3, 0, SEEK_SET);
start_addr3 = (void*)0x80000;
mapped_mem3 = (char*)mmap(start_addr3, 
                         flength3,
                         PROT_READ|PROT_WRITE, 
			 MAP_SHARED, 
	                 fd3,
		         0);
printf("%s\n", mapped_mem3);
while((p3 = strstr(mapped_mem3, "Hello"))) {
      memcpy(p3, "Linux", 5);
      p3 += 5;
}
close(fd3);
munmap(mapped_mem3, flength3);		
return 0;

}
/*
wannian07@wannian07-PC:~$ g++ -o c13 c13.cpp
wannian07@wannian07-PC:~$ ./c13 output.txt
Hello there!

wannian07@wannian07-PC:~$ g++ -o c13 c13.cpp
wannian07@wannian07-PC:~$ ./c13 output.txt
Hello there!
wannian07@wannian07-PC:~$ cat output.txt
Linux there!
*/

本文地址:https://blog.csdn.net/fengye207161/article/details/107278472