Mic_chen

It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

测试程序1:模拟触发OOM程序

/*************************************************************************
    > File Name: hello.c
    > Created Time: Fri 23 Oct 2020 09:40:35 AM CST
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define __USE_LARGEFILE64
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <pthread.h>



// 修改如下开关分别编译两个测试程序在测试平台同时运行
#if 1
#define MB (1024 * 1024)

int main() {
    const size_t size = 205*MB;
    char *buf = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (buf == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }

    size_t written = 0;
    while (1) {
        size_t remaining = size - written;
        if (remaining == 0) {
            written = 0;
        }
        size_t chunk = remaining < MB ? remaining : MB;
        memset(buf + written, 'a', chunk);
        written += chunk;
    }
}
#else

int main(void)
{
    int ret;
    void *status;
	void *ptr = NULL;

	int fd = 0;
	printf("==== oom test ====\r\n");
	unsigned int cnt = 0;	
	
	while(1) 
	{
		//printf("open cnt=%d", cnt);
		ptr = malloc(1*1024);
		cnt++;
		*(char*)ptr = 'a'; // 使用分配的内存
		usleep(10000);
	}

	return 0;
}
#endif

  

测试程序2:fork子进程测试程序

/*************************************************************************
    > File Name: hello.c
    > Created Time: Fri 23 Oct 2020 09:40:35 AM CST
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define __USE_LARGEFILE64
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <pthread.h>
#include <semaphore.h>



#define FILE_SIZE	(100*1024)

pthread_t               thread_id1;
pthread_t               thread_id2;
int fd = 0;
sem_t gt_sem;


char buf_wr[FILE_SIZE] = {0};
char buf_rd[FILE_SIZE] = {0};



int main(void)
{
	printf("+++process %d start running!ppid = %d\n",getpid(),getppid());
    volatile int i = 0;


	pid_t pid = fork();

	if(pid){//父进程
		printf("%2d parent:process %d start running!ppid = %d\n",i++,getpid(),getppid());
		printf("%2d parent:process %d finish running!ppid = %d\n",i++,getpid(),getppid());

		while(1) {
			sleep(1);
		}
	}
	else{//子进程
		printf("%2d child:process %d start running!ppid = %d\n",i++,getpid(),getppid());
		printf("%2d child:process %d finsish running!ppid = %d\n",i++,getpid(),getppid());

	}

	return 0;
}

  

posted on 2023-04-06 15:06  Mic_chen  阅读(42)  评论(0编辑  收藏  举报