可以用來編譯出喫內存進程的代碼段

下面的代碼是根據網上的某一篇博客整理得出的,在實踐中使用過的“用來編譯出喫內存進程的代碼段”。原博客主可以聯繫我加上原始鏈接

實際使用時,會將該段代碼使用實際設備配套的工具鏈編譯出相應的進程,將該進程在設備上後臺運行後並可以主動去喫內存。


#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void eatMem(unsigned int block)
{
    unsigned int i;
    unsigned int j;
    unsigned int nTimes;
    char ch;
    char **pMem;

    /* 每次申請 1M */
    unsigned int cell = 1 * 1024 * 1024;
    pMem = (char **)malloc(sizeof(char *) * block);    
    for (i = 0; i < block; i++) {
        pMem[i] = (char *)malloc(cell);
        if(NULL == pMem[i]) {
            printf("Insufficient memory avalible ,Cell %d Failure\n", i);
            break;
        }

        memset(pMem[i], 0, cell);
        printf("[%u]%u Bytes.\n", i, cell);

        fflush(stdout);
        sleep(1);
    }

    /* Read & Write 100 次, 每次40秒,用來維持佔有的內存一段時間 */
    for (nTimes = 0; nTimes < 100; nTimes++) {
        for(i = 0; i < block; i++) {
            printf("Read&Write [%u] cell.\n", i);
             
            if(NULL == pMem[i]) {
                continue;
            }

            for(j = 0; j < cell; j++) {
                pMem[i][j] = 'a';
                ch = pMem[i][j];
            }
            memset(pMem[i], 0, cell);

            fflush(stdout);
            sleep(1);
        }

        sleep(1);
    }

    printf("Done! Start to release memory.\n");
    //釋放內存核心代碼
    for(i = 0; i < block; i++) {
        printf("free[%u]\n", i);
        if(NULL != pMem[i]) {
            free(pMem[i]);
            pMem[i] = NULL;
        }  

        fflush(stdout);
        sleep(2);
    }

    printf("Operation successfully!\n");
    fflush(stdout);
}

/* gcc test.c -o test, 使用該進程時可以 ./test 30, 表示該進程主動喫30M 的內存 */
int main(int argc,charchar * args[])
{
    if (argc != 2) {
        printf("please input correct parameter\n");
        fflush(stdout);
    }

    unsigned int block = (unsigned int)atoi(argv[1]);
    printf("block is %u\n", block);
    eatMem(block);

    while (1) {
        sleep(10);
    }

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章