views:

442

answers:

3

The question is given like this:

Using the CreateProcess () in the Win32 API. In this instance, you will need to specify a separate program to be invoked from CreateProcess(). It is this separate program that will run as a child process outputting the Fibonacci sequence. Perform necessary error checking to ensure that a non-negative number is passed on the command line.

I have done the following. It doesn't show any error message. When I try to execute it, it exits automatically:

#include <sys/types.h>
#include <windows.h>
#define _WIN32_WINNT 0x0501

#include <stdio.h>

int main()
{

  STARTUPINFO si;   
  PROCESS_INFORMATION  pi;   
  int a=0, b=1, n=a+b,i,ii;  

  ZeroMemory(&si, sizeof(si));

  si.cb = sizeof(si);


  if(! CreateProcess("C:\\WINDOWS\\system32\\cmd.exe",NULL,NULL,NULL,FALSE,0,
                     NULL,NULL,&si,&pi))
    printf("\nSorry! CreateProcess() failed.\n\n");
  else{    
    printf("Enter the number of a Fibonacci Sequence:\n");
    scanf("%d", &ii);

    if (ii < 0)
      printf("Please enter a non-negative integer!\n");
    else
    {         
      {
         printf("Child is producing the Fibonacci Sequence...\n");
         printf("%d %d",a,b);
         for (i=0;i<ii;i++)
         {
            n=a+b;
            printf("%d ", n);
            a=b;
            b=n;
         }
         printf("Child ends\n");
      }

      {
         printf("Parent is waiting for child to complete...\n");
         printf("Parent ends\n");
      }
    }
  }

  WaitForSingleObject(pi.hProcess, 5000);    
  printf("\n");

  // Close process and thread handles.    
  CloseHandle(pi.hProcess);
  CloseHandle(pi.hThread);

  return 0;
}

What am I doing wrong?

A: 

Why are you invoking cmd.exe as your process? The problem states that it's the process that you're launching that should be printing the Fibonacci sequence. You shouldn't be doing it in the main process/app.

What you should have is a separate program that takes in a single argument and prints that many items from the Fibonacci sequence. You main program should ask for a number from the user and then launch the other program by passing in this number as an argument.

Ates Goral
A: 

The question says to spawn a process that outputs a Fibonacci sequence. Get/validate the user input in the main process, then spawn another program (written separately) to print the Fibonacci sequence. Pass the user input to the spawned process as a command-line parameter.

Donnie DeBoer
+2  A: 

I think you misunderstood your exercise. Also, you might want to do handle inheritance while using CreateProcess. This might be above your skill level, but still a useful lesson: http://support.microsoft.com/kb/q190351/

Ori Osherov