Question

Alright, I'm doing a pipe to connect with the children of my process. First of nothing I tried to do a safeguard of my fds so I can access them later for some stuff, but somehow it just gets stuck when duplicating the fds.

int pipeFd [2];
int pid;
pipe (pipeFd);

//Safeguard of the Original FDs
int fdSG [2];
perror ("fdsg create");
dup2 (1, fdSG [1]);
perror ("dup2 sfg1");
dup2 (0, fdSG [0]);
perror ("dup2 sfg2");
dup2 (pipeFd [1], 1);

The program gets stuck in the last instruction showed here.

The terminal output is the following:

fdsg create: Success
dup2 sfg1: Bad file descriptor
dup2 sfg2: Bad file descriptor
dup2: Bad file descriptor

Does any of you have any clue why this is happening?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top