setjmp与longjmp的使用

#include "stdafx.h"
#include  <setjmp.h>  
#include <iostream>
#include <Windows.h>
using namespace std;

jmp_buf	g_objJmp;

void fun();

int main()
{
	while (true)
	{
		switch (setjmp(g_objJmp))
		{
		case -1:
			cout << "stop process err!" << endl;
			return -1;

		case 0:	//run ok
			cout << "run succ" << endl;
			break;

		case 1:
			cout << "err 1" << endl;
			break;

		case 2:
			cout << "err 2" << endl;
			break;

		default:
			cout << "unknow err!" << endl;

			break;
		}

		Sleep(1000);
		
		fun();
	}
}

void fun()
{
	static int nTimes = 0;

	cout << "run times: " << nTimes << endl;

	int nVal = rand() % 3 + 1;

	nTimes++;
	if (10 == nTimes)
	{
		nVal = -1;
	}

	longjmp(g_objJmp, nVal);
}
 

你可能感兴趣的:(windows)