Simvik

Retry only what can succeed

Repeat an operation while it reports a transient error, but stop on a fatal one. A medium embedded C problem (Error handling), run and graded in the browser.

medium · Error handling · error-handling · retry · function-pointers

A sensor read can fail with E_BUSY (try again soon) or a fatal error such as E_NODEV (nothing will fix that). Write with_retry(op, max_tries):

  • call op() up to max_tries times,
  • return E_OK as soon as one call succeeds,
  • return immediately on any error other than E_BUSY, without calling again,
  • if every try was E_BUSY, return E_BUSY after the last one.

Starter code

int with_retry(int (*op)(void), int max_tries) {
  return op();
}

Example tests

Succeeds on the third try

run(E_BUSY, E_BUSY, E_OK, 3, 5);

Expected output:

result=0 calls=3

A fatal error stops at once

run(E_NODEV, E_OK, E_OK, 3, 5);

Expected output:

result=2 calls=1

Learn it first

More Error handling problems