Hi all,

I'm writing this piece of code out in unix. What I want to do is pass an integer argument through the command line and then manipulate it from there. I've done char strings before but cannot seem to get it to work with int's.

Once I have this int number it will contain the number of times I will create a process from fork.

So this is what I have so far:

int main(int ac, *argv[])
{
   if(ac>1)
   prinftf("invalid number of arguments");
   exit(1);
}

Here is the whole main. I want to know if I am doing this correctly.I just want to send one int argument from command-line and be able to convert the argument from string to int hence atoi, then take the int argument and create that number (command line argument) of child processes. Also is there a macro or something to assign random numbers that someone can point me to?

Any help is appreciated and obviously Im not asking anyone to finish this project for me but just to point me in the right direction.

#include	<stdio.h>


main(int ac, char *argv[])
{
	
    if(ac>1)
    {
          printf("Invalid number of arguments /n");
          exit(1);
    }
    else
    {
        int newpid;
        newpid=atoi(argv);
    }
    
    void child_code(), parent_code();
    printf("before: mypid is %d\n", getpid());
    if ( (newpid = fork()) == -1 )
		perror("fork");
	else if ( newpid == 0 )
		child_code(DELAY);
	else
		parent_code(newpid);
}
main(int ac, char *argv[])

Even when you do not specify a return type, main returns int, but your main does not have a return value. If you do not return a value from main, a junk value is returned to the OS. Also, C99 does not support implicit int anymore, so you should be typing it explicitly to futureproof your code.

if(ac>1)
    {
          printf("Invalid number of arguments /n");
          exit(1);
    }

The test is backwards. :) If ac is greater than 1, it means there is an argument available.

else
    {
        int newpid;
        newpid=atoi(argv);
    }

newpid is declared in the else block, so it does not exist outside of that block. Whatever you do with newpid, it will go away when execution gets to the end curly brace for the else block. Also, argv is an array, so you need to specify which item in the array you want to convert to an int.

This code should help you get started. It is always a good idea to start with something small and test that it works before adding more complexity. Like a program to print the arguments and make sure you got that right before trying to spawn processes which is harder to debug:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int isInt(char const* p);

int main(int argc, char *argv[])
{
    int nProcesses = 0;
    int x;

    if (argc < 2)
    {
        fputs("usage: $prog {number of processes}\n", stderr);
        exit(EXIT_FAILURE);
    }

    if (!isInt(argv[1]))
    {
        fputs("integer argument expected\n", stderr);
        exit(EXIT_FAILURE);
    }

    nProcesses = atoi(argv[1]);
    printf("argv[1] = %d\n", nProcesses);

    for (x = 0; x < nProcesses; ++x) printf("spawn process #%d\n", x + 1);

    return 0;
}

int isInt(char const* p)
{
    /* example only, just check for digits */
    /* range check as an exercise for the reader */
    for (; *p; ++p)
    {
        if (!isdigit(*p)) break;
    }

    return *p == '\0';
}

One thing to remember is that atoi() is not good at handling errors. To use it safely the string should be validated beforehand to make sure that it represents an integer value. strtol() has better error handling but is more complicated to use:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    int nProcesses = 0;
    int x;

    if (argc < 2)
    {
        fputs("usage: $prog {number of processes}\n", stderr);
        exit(EXIT_FAILURE);
    }

    {
        char *endp;

        nProcesses = strtol(argv[1], &endp, 0);

        /* endp should point to the end of 
           argv[1] for a successful conversion */
        if (endp == argv[1] || *endp)
        {
            fputs("integer argument expected\n", stderr);
            exit(EXIT_FAILURE);
        }
    }

    printf("argv[1] = %d\n", nProcesses);

    for (x = 0; x < nProcesses; ++x) printf("spawn process #%d\n", x + 1);

    return 0;
}

Also is there a macro or something to assign random numbers that someone can point me to?

In <stdlib.h> you can find rand() and srand():

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int x;

    /* seed on the time for better randomness */
    srand((unsigned)time(NULL));

    for (x = 0; x < 10; ++x)
    {
        int r = rand();

        /* print both [0..RAND_MAX) and [0..100)
           to show how the range might be adjusted */
        printf("%5d %5d\n", r, r % 100);
    }

    return 0;
}

rand() has some pitfalls, so be sure to read these links:
http://c-faq.com/lib/rand.html
http://c-faq.com/lib/randrange.html
http://c-faq.com/lib/srand.html
http://c-faq.com/lib/notveryrand.html
http://c-faq.com/lib/shuffle.html

commented: Thanks! +1
commented: Good explanation and carefully thought out. +22

Thanks, you were a big help. I finished off the code , I figured out what char array to pass to command-line, the srand worked great. Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.