I have two processes on Linux, A & B.
I want to share the file descriptor from process A with process B, now I just serialize it to a char*
and pass it to the execl
parameters, but that doesn't work.
A.c looks like this:
union descriptor{
char c[sizeof(int)];
int i;
} fd;
pid_t pid;
fd.i = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Perform other socket functions
pid = fork();
if(pid == 0){
// Read data from socket
if(execl("./B", fd.c, NULL) < 0){
exit(EXIT_FAILURE);
}else(
exit(EXIT_SUCCESS);
}
}else if(pid < 0){
exit(EXIT_FAILURE);
}else{
waitpid(pid, NULL, 0);
}
B.c looks like this:
union descriptor{
char c[sizeof(int)];
int i;
} fd;
memcpy(&fd.c[0], argv[0], sizeof(int));
write(fd.i, "TEST", 4);
close(fd.i);
But this doesn't work, and I don't really understand why not. How can I make this work? And if it works, is it the best solution to share a file descriptor between a parent and a child after a fork
and a exec
?
Update
The problem is unrelated to the question I asked, it is caused by a wrong way of passing an integer as pointed out by @OliCharlesworth. Please close this question.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…