A regular C program, an implementation of some shell program, which uses standard input to get commands and executes them, in which main() is declared as: int main(int argc, char *argv[]), works normally. It's a small shell program that prints a prompt and waits for user input in a loop, and executes the command entered. However I want to make the commandline parameters invisible when invoked, as follows:
- rename the main() function to old_main().
- create a new main() function that:
- Copies the argv[] string array to a new array, and then
- Erases the original argv[] structure.
- Forks itself and in the child calls old_main with the saved commandline parameters, and exits the parent process.
This works as 'ps -ef' now shows the command run without the commandline arguments displayed. However, the program now behaves different, and does not wait for user-input, but keeps printing the prompt. Even Ctrl-C does not work anymore.
If, however, I call the program as:
$ echo quit | ./newprog
The command 'quit' is executed (causing the program to exit), so the program still works when the stdin is redirected, but does not work in interactive mode.
Below the new program that forks itself and in the child calls the old main with the saved commandline parameters.
/* newprog.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_NARGS 40
extern int old_main(int nargc, char *nargv[]);
int main(int argc, char *argv[])
{
int i; pid_t pid;
int nargc=argc;
char *nargv[];
nargv[0]=argv[0];
for (i = 1; i < argc; i++)
{
nargv[i]=strdup(argv[i]);
memset(argv[i],0,strlen(argv[i]));
}
nargv[i]=NULL;
pid=fork();
if (pid == 0) return old_main(nargc, nargv); /* child calls old_main() */
else if (pid == -1) printf("error: fork()\n");
exit(0); /* exit parent */
}