1.c

来源:互联网 发布:数据报送管理办法 编辑:程序博客网 时间:2024/06/06 04:54
#include <sys/shm.h>


#define TEXT_SIZE 4096


struct share_use_st 
{
    int iFlag;  // 0: write, 1: read
    int iSize;
    char cText[TEXT_SIZE];
};


void* shm = NULL;
struct share_use_st *pShared;
int shmid;    
FILE* pFp;
FILE* pWriteFp;
char cBuf[TEXT_SIZE];
int iSize;
pid_t fatherId;
pid_t sonId;


void readDate();


void catchFatherSigUsr1(int sig)
{
    readDate();
}


void readDate()
{
    if (iSize=fread(cBuf, 1, TEXT_SIZE, pFp)) > 0)
    {
        memset(pShared->cText, 0, TEXT_SIZE);
        memcpy(pShared->cText, cBuf, iSize);
        pShared->iSize = iSize;
        pShared->iFlag = 1; // ready to read
        kill(sonId, SIGUSR1);
    }
    // read End
    else if (0 == iSize)
    {
        kill(sonId, SIGUSR2);
    }
}


int main(int argc, char** argv)
{
    pFp = fopen("input.txt", "r");
    if (NULL == pFp)
    {
        printf("open file failed\n");
        return -1;
    }


    
    shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666|IPC_CREAT);
    if (-1 == shmid)
    {
        printf("create shmget failed\n");
        fclose(pFp);
        return -1;
    }


    shm = shmat(shmid, 0, 0);
    if (shm == (void*)-1)
    {
        cout << "shmat failed" << endl;
        fclose(fp);
        return -1;
    }


    cout << "shm =" << shm << endl;


    pShared = (struct share_use_st*)shm;
    pShared->iFlag = 0; // write


    fatherId = getpid();    // get the fatherId
    if ((sonId=fork()) < 0)
    {
        printf("fork failed\n");
        return -1;
    }
    else if (0 == sonId)
    {
        
    }
    else
    {
        // start to read file and write to share memory
        readDate();
    }




    


    fclose(pFp);
    
}

0 0
原创粉丝点击