From the code you've shown you haven't initalised fdSG
. That's not correct, the arguments of dup2
both need to be valid file descriptors.
Since you seem to want to copy a fd rather than replace an existing one you should use dup
for those backup copies instead, it picks a free fd
and uses that. (Alternatively you could initalise fdSG
to be valid fds too).
From the manpage:
dup()
uses the lowest-numbered unused descriptor for the new descriptor.