文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Unix和Windows高级编程: 共享IO

Unix和Windows高级编程: 共享IO

时间:2010-11-15  来源:kgisme170

        打开一个文件描述符(句柄),一个进程(线程)来写,一个进程(线程)来读。这是可以做到的,不用多次打开这个文件,但是写端必须刷新缓冲,并且读端必须把文件指针进行重置。

源代码1: unix下用多进程实现:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
int main(void){
        int fd=open("my.txt",O_RDWR|O_CREAT,S_IRWXU);
        if(0==fd){
                printf("open failed\n");
                return 1;
        }
        pid_t p=fork();
        char buf[20];
        if(p){//father

                wait(0);
                lseek(fd,0,SEEK_SET);
                if(6!=read(fd,buf,sizeof(buf))){
                        printf("read error %d:%s\n",errno,strerror(errno));
                        return 1;
                }
                printf("content read:%s\n",buf);
                close(fd);
        }else if(0==p){
                write(fd,"hello",6);
                sync();
        }
        return 0;
}

程序输出:
> ./a.out
content read:hello

源代码2: windows下用多线程实现:

#include "stdafx.h"
#include<windows.h>
#include<stdio.h>
HANDLE hFile;
void* fun(void*){
    char hw[]="helloworld";
    DWORD dwWriten;
    if(!WriteFile(hFile,(LPVOID)hw,sizeof(hw),&dwWriten,NULL)){//ERROR_ACCESS_DENIED(5)

        printf("WriteFile failed:%d\n",GetLastError());
    }
    if(!FlushFileBuffers(hFile)){
        printf("Flush failed\n");
    }
    return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
    hFile=CreateFile("d:\\my.txt",
        GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_WRITE|FILE_SHARE_READ,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(INVALID_HANDLE_VALUE==hFile){
        printf("CreateFile failed:%d\n",GetLastError());
        return 1;
    }
    HANDLE hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)fun,NULL,0,NULL);
    if(NULL==hThread){
        printf("CreateThread failed:%d\n",GetLastError());
        return 1;
    }
    WaitForSingleObject(hThread,INFINITE);
    SetFilePointer(hFile, 0, 0, FILE_BEGIN);
    char buf[20]={0};
    DWORD dwRead;
    if(!ReadFile(hFile,(LPVOID)buf,20,&dwRead,NULL)){
        printf("ReadFile failed:%d\n",GetLastError());
        return 1;
    }
    printf("content read:%s\n",buf);
    CloseHandle(hFile);
    return 0;
}

程序输出:
content read:helloworld
Press any key to continue . . .

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载