I am supposed to create a chain of N processes, where N is the command line parameter. Each process creates a child process, prints out its own PID and its parent's PID, and then waits for its child to terminate by calling the wait() function.

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (int argc, char *argv[]) 
{
    pid_t childpid = 0; 
    int i, nbrOfProcesses;

    if (argc != 2) {   
        fprintf(stderr, "Usage: %s <processes>\n", argv[0]);
        return 1; 
    }

    nbrOfProcesses = atoi(argv[1]);

    for (i = 0; i < nbrOfProcesses; i++) {
        childpid = fork();
        if (childpid == -1) {
            perror("Fork failed");
            exit(1);
        }
        else if (childpid != 0) {

            printf("i: %d  process ID: %4d  parent ID: %4d  child ID: %4d\n", i+1, getpid(), getppid(), childpid);
            break;
        }
    }

    wait(NULL);
    return 0; 

    }

The response i Get is this:
[rajp1@gator lab6]$ ./chainofn
Usage: ./chainofn <processes>
What am i Doing wrong?
Any Advise will help
Thanks

Recommended Answers

All 3 Replies

The code says you need at least 1 argument, the number of processes to run. IE, you need to execute it as ./chainofn N where N is the number of processes. You are not specifying that argument, hence the error.

This code was given by my professor for practice. He wants us to see the output it gives.

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.