Find the answer to your Linux question:
Results 1 to 3 of 3
Hi! I am working with fork() and execv() commands for first time. Reading through the manuals I wrote following code in C on unix sys. which went into infinite process ...
  1. #1
    Just Joined!
    Join Date
    Sep 2007
    Posts
    2

    Unhappy Problem with fork() / execvp()

    Hi! I am working with fork() and execv() commands for first time. Reading through the manuals I wrote following code in C on unix sys. which went into infinite process creation. I failed completely in figuring out what is happening.

    Here is the code...

    int main()
    {
    char *path="hello$";
    char command[100];

    while(1)
    {
    printf("%s",path);
    scanf("%s",command);
    if(!strcmp(command,"exit"))
    {
    printf("\n thanks for using this shell\n");
    break;
    }
    else{
    if(fork()==0)
    execvp(command,NULL);
    }
    }
    return 0;
    }

    This program is supposed to create a process with whatever string provided my user (i.e. me). I tried to run the program with random ip. The program went into infinite process creation. Can anyone help? Thanx in advance...

  2. #2
    Just Joined!
    Join Date
    Feb 2007
    Location
    pilani,india
    Posts
    4
    hiiii...
    there is a small problem with your code...
    execvp(command,NULL) is to be executed by the child......the child is supposed to execute the command and die....
    this works fine until the command you've entered is a valid one because execvp executes the command and kills the child...........but if the command entered is an invalid command,execvp returns -1 and doesn't kill the child.....then infinetely many processes will be created as you keeps on entering commands.....
    so the program should be...

    int main()
    {
    int i;
    char *path="hello$";
    char command[100];

    while(1)
    {
    printf("%s",path);
    scanf("%s",command);
    if(!strcmp(command,"exit"))
    {
    printf("\n thanks for using this shell\n");
    break;
    }
    else{
    if((i=fork())==0)
    execvp(command,NULL);
    if(i==0)
    {
    printf("invalid command, enter a valid one\n");
    exit(1);}
    }
    }
    return 0;
    }

  3. #3
    Just Joined!
    Join Date
    Sep 2007
    Posts
    2
    Thanx for reply.

    But the way I understood it, both the process should halt at scanf and wait for further input. Instead it went into infinite loop of process creation without any further ip!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...