实例要求: 使用多进程
复制同一个文件内容; 实例分析: 1.创建一个父进程和一个子进程
,设置光标
在指定文件中的偏移量
,实现对同一个文件的复制。 2.比如:可以指定子进程复制文件内容的前一半
,而父进程复制文件内容的后一半
。 3.根据时间片轮询法则
,最终父进程和子进程可以把同一个文件复制成功。 相关的文件IO接口函数如下: open函数:
# include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> int open ( const char * pathname, int flags, mode_t mode) ;
# include <unistd.h> int close ( int fd) ;
# include <unistd.h> ssize_t read ( int fd, void * buf, size_t count) ;
# include <unistd.h> ssize_t write ( int fd, const void * buf, size_t count) ;
# include <sys/types.h> # include <unistd.h> off_t lseek ( int fd, off_t offset, int whence) ;
# include <sys/types.h> # include <unistd.h> pid_t fork ( void ) ;
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
# include <stdbool.h>
int get_src_file_size_and_create_dest_file ( const char * src_file, const char * dest_file) ;
void cp_src_file_to_dest_file ( const char * src_file, const char * dest_file, int offset, int size) ; int main ( int argc, char const * argv[ ] )
{ if ( 3 != argc) { printf ( "Usage : %s src_file dest_file\n" , argv[ 0 ] ) ; return - 1 ; } int size = 0 ; size = get_src_file_size_and_create_dest_file ( argv[ 1 ] , argv[ 2 ] ) ; pid_t pid = 0 ; if ( - 1 == ( pid = fork ( ) ) ) { perror ( "fork error" ) ; return - 1 ; } else if ( 0 == pid) { cp_src_file_to_dest_file ( argv[ 1 ] , argv[ 2 ] , 0 , size/ 2 ) ; } else if ( 0 < pid) { cp_src_file_to_dest_file ( argv[ 1 ] , argv[ 2 ] , size/ 2 , size - size/ 2 ) ; } return 0 ;
} int get_src_file_size_and_create_dest_file ( const char * src_file, const char * dest_file)
{ int src_fd = open ( src_file, O_RDONLY) ; if ( - 1 == src_fd) { perror ( "open error" ) ; return - 1 ; } int size = lseek ( src_fd, 0 , SEEK_END ) ; int dest_fd = open ( dest_file, O_WRONLY | O_CREAT | O_TRUNC, 0666 ) ; if ( - 1 == dest_fd) { perror ( "open error" ) ; return - 1 ; } return size; } void cp_src_file_to_dest_file ( const char * src_file, const char * dest_file, int offset, int size)
{ int src_fd = 0 ; int dest_fd = 0 ; if ( - 1 == ( src_fd = open ( src_file, O_RDONLY) ) ) { perror ( "open error" ) ; exit ( - 1 ) ; } if ( - 1 == ( dest_fd = open ( dest_file, O_WRONLY) ) ) { perror ( "open error" ) ; exit ( - 1 ) ; } lseek ( src_fd, offset, SEEK_SET ) ; lseek ( dest_fd, offset, SEEK_SET ) ; int ret = 0 ; int num = 0 ; char buf[ 64 ] = { 0 } ; while ( true) { ret = read ( src_fd, buf, sizeof ( buf) ) ; if ( 0 == ret) { break ; } num += ret; if ( num > size) { write ( dest_fd, buf, size - ( num - ret) ) ; break ; } write ( dest_fd, buf, ret) ; } close ( src_fd) ; close ( dest_fd) ; }
linux@ubuntu: ~ $ gcc proc2. c
linux@ubuntu: ~ $ . / a. out k1. c k2. c
linux@ubuntu: ~ $ diff k1. c k2. c
linux@ubuntu: ~ $