zoukankan      html  css  js  c++  java
  • Linux之文件通信

    /*
     * 后执行,尝试读取另外一个进程写入文件的内容
     */
    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <string.h>
    
    int main(void)
    {
        char buf[1024];
        char *str = "----------test2 write secesuss--------
    ";
        int ret;
    
        sleep(2);   //睡眠2秒,保证test1将数据写入test.txt文件
    
        int fd = open("test.txt", O_RDWR);
    
        //尝试读取test.txt文件中test1写入的数据
        ret = read(fd, buf, sizeof(buf));   
    
        //将读到的数据打印至屏幕
        write(STDOUT_FILENO, buf, ret);
    
        //写入数据到文件test.txth中, 未修改读写位置
        write(fd, str, strlen(str));
    
        printf("test2 read/write finish
    ");
    
        close(fd);
    
        return 0;
    }
    /*
     * 先执行,将数据写入文件test.txt
     */
    #include <stdio.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define N 5
    
    int main(void)
    {
        char buf[1024];
        char *str = "--------------secesuss-------------
    ";
        int ret;
    
        int fd = open("test.txt", O_RDWR|O_TRUNC|O_CREAT, 0664);
    
        //直接打开文件写入数据
        write(fd, str, strlen(str));
        printf("test1 write into test.txt finish
    ");
    
        sleep(N);
    
        lseek(fd, 0, SEEK_SET);
        ret = read(fd, buf, sizeof(buf));
        ret = write(STDOUT_FILENO, buf, ret);
    
        if (ret == -1) {
            perror("write second error");
            exit(1);
        }
    
        close(fd);
    
        return 0;
    }
  • 相关阅读:
    nginx编译安装
    使用scp命令,不同服务器之间拷备文件
    cpu负载过高排查与解决
    Docker安装
    sftp安装
    nginx登陆验证 [done]
    git常用命令
    python常见问题记录
    升级openssl
    rsync使用
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11317661.html
Copyright © 2011-2022 走看看