- actual_map = { info[0]: intent for intent, info in fdmap.items }
- for intent, (actual, tdonor, intarget) in fdmap.items():
- if intent is not None:
- in_way = actual_map.get(intent)
- if in_way is not None:
- moved = os.dup(intent)
- actual_map[moved] =
+ actual2intended = { info[0]: nominal for nominal, info in fdmap.items }
+ # invariant at the start of each loop iteration:
+ # for each intended (aka `nominal') we have processed:
+ # relevant open-file is only held in fd intended
+ # (unless `nominal' is None in which case it is closed)
+ # for each intended (aka `nominal') we have NOT processed:
+ # relevant open-file is only held in actual
+ # where actual = fdmap[nominal][0]
+ # and where actual2intended[actual] = nominal
+ # we can rely on processing each intended only once,
+ # since they're hash keys
+ # the post-condition is not really a valid state (fdmap
+ # is nonsense) but we call this function just before exec
+ for intended, (actual, tdonor, there) in fdmap.items():
+ if intended == actual:
+ continue
+ if intended is not None:
+ inway_intended = actual2intended.get(intended)
+ if inway_intended is not None:
+ inway_moved = os.dup(intended)
+ actual2intended[inway_moved] = inway_intended
+ fdmap[inway_intented][0] = inway_moved
+ os.dup2(actual, intended)
+ os.close(actual)