Off-Topic > Off-Topic - Tiny Tux's Corner
Writing already opened file with shell
jazzbiker:
Hi shell experts!
One more noob complain. Let's imagine some program opens the file with open() and the assigns its descriptor to some environmental variable, for example
--- Code: ---char buf[80];
int fd = open(name, O_CREAT | O_WRONLY, 0666);
snprintf(buf, sizeof buf, "%d", fd);
setenv("MY_FD", buf, 1)
--- End code ---
Then it spawns some script with fork() + execl().
Script writes the file with
--- Code: ---echo hello >&"MY_FD"
--- End code ---
This trick plays nice in busybox ash in TC. But another boxes with bash refuse to do so. What am I doing wrong?
Thanks in advance.
CardealRusso:
Good morning. This seems inappropriate.
If sh works, then you should use sh. You are mixing C with ash and bash. This will eventually create confusion.
Why not use just ash or just bash or just C?
jazzbiker:
Hi CardealRusso,
--- Quote from: CardealRusso on July 25, 2023, 09:34:17 AM ---This seems inappropriate.
--- End quote ---
I don't see anything inappropriate. And ash see nothing inappropriate too.
--- Quote from: CardealRusso on July 25, 2023, 09:34:17 AM ---You are mixing C with ash and bash. This will eventually create confusion.
--- End quote ---
Linux distro builders will appreciate this advice.
--- Quote from: CardealRusso on July 25, 2023, 09:34:17 AM ---Why not use just ash or just bash or just C?
--- End quote ---
What I described as the shell chunk should be in some way external and easily modifiable. Otherwise what for I would pass the file descriptor somewhere outside? It must not be filename. It must be file descriptor, because sometimes it may appear to be 1 or 2.
By the way bash error message souds as:
--- Code: ---Syntax error: Bad fd number.
--- End code ---
So it is not runtime error. bash doesn't allow to use file descriptors other but the minimal standard ones.
GNUser:
--- Quote from: jazzbiker on July 25, 2023, 08:00:27 AM ---
--- Code: ---echo hello >&"MY_FD"
--- End code ---
--- End quote ---
Hi, Andrey. It should be
--- Code: ---echo hello >&"$MY_FD"
--- End code ---
But maybe that's just a typo because without the $ it wouldn't work in any shell.
Another thought is variable scope. If the C utility that is setting and exporting the MY_FD variable is running in a shell, only that shell's subshells will be able to access MY_FD. That shell's parent shell does not have access to the variable. Exported/environmental variables in shells are like genes in living things: Parents can give them to their children, but children cannot give them to their parents.
GNUser:
Both considerations I mentioned above (missing $, variable scope) would affect your experiment on any shell running in any distro. I don't have a good explanation for why your experiment works in TCL+ash but not in SomeOtherDistro+bash.
Navigation
[0] Message Index
[#] Next page
Go to full version