Help with some C

Max Okumoto okumoto at ucsd.edu
Sat Apr 23 01:03:40 PDT 2005


PJ Hyett wrote:
I'm trying my hand with a little unix programming, but my second
execvp in main() below doesn't appear to be working correctly.
A sample call to this would be ./rungenerator 20 1 and the output is as follows:
parent: 27461
child: 27462
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
child: 27463
the output should be:
parent: 27461
child: 27462
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
child: 27463
1 3 5...etc
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char* argv[]){
Style issue most people prefer if the function name
starts on the first column.  This way people can find
functions definitions by searching for "^main(".
int
main(int argc, char *argv[])
{
  int fd[2];
  pid_t child[2];
  char *args[4];
  if(argc != 3){
Style issue put space between {if, while, switch} and
the parenthesis.
    write(2,"Invalid # of arguments\n",23);
Use printf() here.

    return 1;
  }
  args[0]="./generate1";
  args[2]=argv[1];
  args[3]=argv[2];
  args[4]="0";
"0" is not equal to NULL

The array args[] has a range from 0 to 3.  args[4] is not a
valid location to write/read anything.
  printf("parent: %ld\n",(long) getpid());

  if(child[0] = fork())
    child[1] = fork();
  if(!child[0]){
    printf("child: %ld\n",(long) getpid());
    args[1]="even";
    execvp(args[0],args);
  }
  if(!child[1]){
    printf("child: %ld\n",(long) getpid());
    args[1]="odd";
    execvp(args[0],args);
  }
  return 0;
}
here's the code to generate1 if you're curious:
int main(int argc, char* argv[]){
  int which, i, num, fd;
  char buf[3];
  if(argc != 4){
    write(2,"Invalid # of arguments\n",23);
    return 1;
  }
  if(!strcmp(argv[1],"odd"))
    which=1;
  else if(!strcmp(argv[1],"even"))
    which=2;
  else{
    write(1,"Must be odd or even!\n",21);
    return 2;
  }
  srand(which);

  fd = atoi(argv[3]);

  /* if we're counting 0 as even */
  if(which==2)
    write(fd,"0 ",2);
  num = atoi(argv[2]) * 2;
  for(i=which;i<num;i=i+2){
Style issue put spaces after the semicolons in
 for (i = xxx; i < yyy; i += 2) {
 }
    sprintf(buf,"%d ",i);
    write(fd,buf,3);
  }
  write(fd,"\n",1);
  return 0;
}
Any help would be appreciated. Thanks, PJ.







More information about the Users mailing list