Recently I started to look into some operating system's source code, there is a special coding technique which puzzles me a lot.
First the source code declare a very basic struct, such as:
struct cmd {
int type;
};
And then, it continue to declare several other structs which contain the first basic struct at their beginning:
struct execcmd {
int type; //Here.
char *argv[MAXARGS];
char *eargv[MAXARGS];
};
struct redircmd {
int type; //Here.
struct cmd *cmd;
char *file;
char *efile;
int mode;
int fd;
};
Because the identity in the first few bytes of these structs, we are able to access the shared int type part even though we are not sure of which exactly the structure it is. And we can use the int type part to cast the struct pointer to the correct one:
void runcmd(struct cmd *cmd)
{
switch(cmd->type){
case EXEC:
ecmd = (struct execcmd*)cmd;
case REDIR:
rcmd = (struct redircmd*)cmd;
break;
case LIST:
lcmd = (struct listcmd*)cmd;
break;
case PIPE:
pcmd = (struct pipecmd*)cmd;
break;
case BACK:
bcmd = (struct backcmd*)cmd;
break;
}
So my question is, what is the name and benefit of this techinique, or, what is the normal use case for this technique?
smart union