Sunday 20 November 2011

How can I run another program during my program’s execution?in C programming

How can I run another program during my program’s execution?

As seen in the preceding example, the spawn family of functions allows one application to start another application, then return to the original application when the first one is finished. Read FAQ XX.10 for a good background dose of spawn and for example code (all you have to do is change _P_OVERLAY to _P_WAIT and you’re done).

However, there is another way to accomplish this task that needs to be mentioned. This other method  involves the system() call. The system() function is similar to, but still different from, the exec or spawn functions. In addition to suspending the current application to execute the new one (instead of killing it), system() launches the COMMAND.COM command interpreter (or whatever command interpreter is  running on your machine) to run the application. If COMMAND.COM or its equivalent cannot be found, the application is not executed (this is not the case with exec and spawn). The following example is yet another version of a call to EDIT.COM to open a file, whose name arrives from the example program’s command
line:
#include <stdio.h>
#include <process.h>
#include <stdlib.h>
char argStr[255];
void
main(int argc, char ** argv)
{
int ret;
/* Have EDIT open a file called HELLO if no arg given */
sprintf(argStr, “EDIT %s”, (argv[1] == NULL ? “HELLO” : argv[1]));
/* Call the one with variable arguments and an environment */
ret = system(argStr);
printf(“system() returned %d\n”, ret);
}

As it was with the earlier example (using _P_WAIT), the printf() statement after the system() call is executed
because the initial program was merely suspended and not killed. In every case, system() returns a value that
signifies success or failure to run the specified application. It does not return the return code from the application itself.

Cross Reference:

XX.10: How can I run another program after mine?

No comments:

Post a Comment