sbzainal
asked on
Unix system command substitution in C
Hi Experts,
I wanted to write events (errors, etc) relating to a program to a logfile using the Unix command while in a C program e.g. :
case 1: /* Key error message for shared memory */
system("date >> $MYLOG | echo Error in obtaining key to shared memory!(DCSF) >> $MYLOG");
system("logger -f $MYLOG ");
exit(1);
Note that the $MYLOG is just to represent a logfile which in the actual case is the value of a C variable cLogFileName which is updated from a config file. (In this case, cLogFileName equals a value "../data/logfile01.dat" ). My question is how can I substitute the value of a C variable into the Unix shell command so that the Unix command appends to the physical file (in this case ../data/logfile01.dat) ??
Thanks in advance.
I wanted to write events (errors, etc) relating to a program to a logfile using the Unix command while in a C program e.g. :
case 1: /* Key error message for shared memory */
system("date >> $MYLOG | echo Error in obtaining key to shared memory!(DCSF) >> $MYLOG");
system("logger -f $MYLOG ");
exit(1);
Note that the $MYLOG is just to represent a logfile which in the actual case is the value of a C variable cLogFileName which is updated from a config file. (In this case, cLogFileName equals a value "../data/logfile01.dat" ). My question is how can I substitute the value of a C variable into the Unix shell command so that the Unix command appends to the physical file (in this case ../data/logfile01.dat) ??
Thanks in advance.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
forgot, if you want to control environment variables for child programs, you can use the setenv() call:
setenv( "MYLOG", cLogFileName, 1 );
Then, a script, or program, is launched through system(), that uses this environment variable, should get the value set here (only for children, cannot pass environment to parents!)
setenv( "MYLOG", cLogFileName, 1 );
Then, a script, or program, is launched through system(), that uses this environment variable, should get the value set here (only for children, cannot pass environment to parents!)
I would AVOID using system() for this kind of thing. It generates at least two tasks, one the user shell, the other a copy of "echo". That's okay if these tasks are going to do a lot of work for you, but these do very little. These calls are going to be about 99% overhead.
How about using syslog() or good old fopen( "...", "a+" ) ??
How about using syslog() or good old fopen( "...", "a+" ) ??
use syslog()
http://www.die.net/doc/linux/man/man2/syslog.2.html
If you still insist on your method, use sprintf
char command[128];
sprintf (command, "date >> %s blah blah", my_c_variable);
snprintf is a safer version of sprintf that you can use for added security
Sunnycoder