TIP: Click on subject to list as thread! ANSI
echo: muffin
to: Bo Simonsen
from: Wes Garland
date: 2003-06-22 10:00:28
subject: fconf2maximus

Good work!
 
> * To avoid it crashes under strcmp, because argv[i] is null */
 
argv[argc] by definition is NULL. Change your loop invariant to "i
< argc", and you can remove that check.
 
Also, you should learn how to use getopt() to process your argument vector;
it's the "standard" way of doing things under UNIX, and is
completely portable as long as you don't rely on the getopt_long()
extensions (e.g. --option-name) under Linux. getopt() will documented in
your man pages, probably in section 2.
 
After you open your file, it is always a very good idea to lock it! flock()
is moderately portable, and if you are on a platform which is missing it,
linking with libcompat.so from the Maximus distribution will provide it.
(Alternatively, you could also use sopen() in that same library, but I
wouldn't recommend it).
 
A few options exist for your style of output:
- open the file and block until you can overwrite it
- open the file, and fail if somebody else has it locked
- create a temp file, and move it over when you're done, after you have a
lock on the target.
 
The third option is the most robust for the type of output you're
generating: it insures that if squish runs at the same time as your program
that squish will *always* get a "sane" (not half written)
configuration file.
 
Something like this will work very well:
 
char filename[FILENAME_MAX];
 
snprintf(filename, sizeof(filename), "%s.tmp.%i",
squish_cfg_name, (int)getpid());
 
file = fopen(filename, "w");
createSquishConfig(filename);
fclose(file);
 
file = fopen(squish_cfg_name, "r+"); /* open for write, do not overwrite */
if (flock(fileno(file), LOCK_EX))
{
  fprintf(stderr, "Unable to acquire lock for %s! (%s)",
squish_cfg_name, strerror(errno));
  unlink(filename);
  exit(1);
}
 
if (rename(filename, squsih_cfg_name))
{
  fprintf(stderr, "Unable to rename %s to %s! (%s)", filename,
squish_cfg_name, strerror(errno));
  unlink(filename);
  exit(1);
}
 
fclose(file);
printf("Done\n");
return 0;
 
...you get the idea. BTW, no critcism here, just a guy who's been around
the block a few times helping out the younger generation. :)
 
Cheers,
Wes

--- Maximus/2 3.01
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)
SEEN-BY: 633/267 270
@PATH: 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.