0

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

Edited by P

3
Contributors
3
Replies
25
Views
1 Year
Discussion Span
Last Post by P
0

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.

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.