Linux file of communication

/ * 
 * After the execution, another process tries to read the contents written to the file 
 * / 
#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include < String .h> int main ( void ) 
{ char buf [ 1024 ];
     char * STR = " ---------- -------- secesuss Write test2 \ n- " ;
     int RET; 
    SLEEP ( 2 );    // sleep 2 seconds, to ensure that the data is written test1 test.txt file int FD = Open ( " test.txt "


    


    , O_RDWR); 

    // try to read the file test.txt test1 data written 
    RET = Read (FD, buf, the sizeof (buf));    

    // the read print data to the screen 
    write (STDOUT_FILENO, buf, ret ); 

    // write data to the file test.txth unmodified write position 
    write (FD, STR, strlen (STR)); 

    the printf ( " test2 Read / write Finish \ n- " ); 

    Close (FD); 

    return  0 ; 
}

 

/ * 
 * Before execution, writing data to files 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 \ the n- " ;
     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\n");

    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;
}

 

Guess you like

Origin www.cnblogs.com/wanghao-boke/p/11317661.html